【发布时间】:2018-11-25 10:08:09
【问题描述】:
我正在处理一个相当大的数据集(超过 4 GB),它是我在pandas 中导入的。该数据集中的相当多的列是简单的真/假指示符,自然地,最节省内存的存储这些列的方法是为此列使用bool dtype。但是,该列还包含一些我想保留的 NaN 值。现在,这导致列具有 dtype 浮点数(值 1.0、0.0 和 np.nan)或对象,但它们都使用了太多内存。
举个例子:
df = pd.DataFrame([[True,True,True],[False,False,False],
[np.nan,np.nan,np.nan]])
df[1] = df[1].astype(bool)
df[2] = df[2].astype(float)
print(df)
print(df.memory_usage(index=False, deep=True))
print(df.memory_usage(index=False, deep=False))
结果
0 1 2
0 True True 1.0
1 False False 0.0
2 NaN True NaN
0 100
1 3
2 24
dtype: int64
0 24
1 3
2 24
dtype: int64
什么是存储这些值的最有效方法,知道它们只能采用 3 种不同的值:True、False 和 <undefined>
【问题讨论】:
标签: python python-3.x pandas memory nan