我想知道是否可以要求 pandas 中的 get_dummies 函数输出 dtype 比默认 float64 更轻的虚拟数据帧。
因此,对于具有分类列的示例数据框:
In []: df = pd.DataFrame([(blue,wood),(blue,metal),(red,wood)],
columns=['C1','C2'])
In []: df
Out[]:
C1 C2
0 blue wood
1 blue metal
2 red wood
得到假人后,它看起来像:
In []: df = pd.get_dummies(df)
In []: df
Out[]:
C1_blue C1_red C2_metal C2_wood
0 1 0 0 1
1 1 0 1 0
2 0 1 0 1
这完全没问题。但是,默认情况下 1 和 0 是 float64:
In []: df.dtypes
Out[]:
C1_blue float64
C1_red float64
C2_metal float64
C2_wood float64
dtype: object
我知道之后我可以使用 astype 更改数据类型:
In []: df = pd.get_dummies(df).astype(np.int8)
但我不想让内存中有 float 的数据帧,因为我正在处理一个大数据帧(来自大约 ~5Gb 的 csv)。我想直接将假人作为整数。
请您参考如下方法:
有一个 Unresolved 问题 w.r.t.这个,看这里:https://github.com/pydata/pandas/issues/8725
