在pandas中存储bool和NaN值的内存有效方法

kon*_*wka 2 python memory nan python-3.x pandas

我正在使用我导入的相当大的数据集(超过4 GB)pandas.此数据集中的相当一些列是简单的True/False指标,当然,存储这些bool列的内存效率最高的方法是使用此列的dtype.但是,该列还包含一些我想要保留的NaN值.现在,这导致列具有dtype float(带有值1.0,0.0np.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))
Run Code Online (Sandbox Code Playgroud)

结果是

       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
Run Code Online (Sandbox Code Playgroud)

什么是存储这些类型的值的最有效的方式,因为他们知道自己只能拿3个不同类型的值:True,False<undefined>

Att*_*son 7

使用dtype: int8

1 = True
0 = False
-1 = NaN
Run Code Online (Sandbox Code Playgroud)

这比4倍好float32,8倍好float64