Skip to main content
 首页 » 编程设计

python之Pandas 类别的计算

2024年12月31日15jackei

是否仍然可以使用分类数据类型进行计算?

如果不是,我如何减少具有分类整数的 RAM 使用(非常大的 10m+ 条目表,只有约 500 个唯一整数)。所有计算都必须作为 1 个数组完成。

df = pd.DataFrame({'a':[1,2,3,2,1,3,4,5,6,7], 
                   'b':[1,2,3,2,1,3,4,5,6,7]}) 
df['a'] = df['a'].astype('category') 
df['a'] * df['b'] 

在 Pandas 0.20.3 中:

Out[23]:  
0     1 
1     4 
2     9 
3     4 
4     1 
5     9 
6    16 
7    25 
8    36 
9    49 
dtype: int64 

这不再适用于较新的 pandas 版本(例如 v0.23.0)

TypeError: Series cannot perform the operation * 

我现在需要为更新的 pandas 版本重构我的代码,但是有没有办法维持提供的减少 RAM 消耗的类别?

请您参考如下方法:

作为目前的解决方法,您可以使用 numpy's basic integer types 之一:

import numpy as np 
df = pd.DataFrame({'a':[1,2,3,2,1,3,4,5,6,7], 
                   'b':[1,2,3,2,1,3,4,5,6,7]}) 
df['a'] = df['a'].astype(np.int8) 
df['b'] = df['b'].astype(np.int8) 
>>> df['a'] * df['b'] 
0     1 
1     4 
2     9 
3     4 
4     1 
5     9 
6    16 
7    25 
8    36 
9    49 
dtype: int8 

请注意,这让您有责任注意溢出。