gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 20:33:17 24 4
gpt4 key购买 nike

我正在处理相当大的数据集(超过 4 GB),我在 pandas 中导入了它.这个数据集中有相当多的列是简单的 True/False 指示符,自然地,存储这些列的最节省内存的方法是使用 bool。此列的数据类型。但是,该列还包含一些我想保留的 NaN 值。现在,这导致该列具有 dtype float(值为 1.00.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))

结果

       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>

最佳答案

使用数据类型:int8

1 = True
0 = False
-1 = NaN

这比 float32 好 4 倍,比 float64 好 8 倍

关于python - 在 pandas 中存储 bool 和 NaN 值的内存有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50877663/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com