Pandas value_counts(normalize=True)给出了“IntegerArray”对象没有属性“sum”

2024-09-29 02:19:54 发布

您现在位置:Python中文网/ 问答频道 /正文

使用扩展数据类型时,value_counts(normalize=True)失败。例如,当创建包含pd.NAint8系列时,通常会使用Int8扩展数据类型,但会出现错误:AttributeError: 'IntegerArray' object has no attribute 'sum'。解决办法是什么

pd.Series([1,pd.NA],dtype='Int8').value_counts(normalize=True)

Tags: notrueobjectvalue错误int8pdattributeerror
2条回答

这被认为是一个回归错误,请参见GH33317。好消息是,这是固定在熊猫1.1

pd.__version__  
# '1.1.0.dev0+2004.g8d10bfb6f'

pd.Series([1, pd.NA], dtype='Int8').value_counts(normalize=True) 

1    1.0
dtype: float64

更多示例

s = pd.Series([1, 1, 1, 2, 2, 3, pd.NA], dtype='Int8') 
s.value_counts()
 
1    3
2    2
3    1
dtype: Int64

s.value_counts(normalize=True)

1    0.500000
2    0.333333
3    0.166667
dtype: float64

s.value_counts(normalize=True, dropna=False)

1      0.428571
2      0.285714
NaN    0.142857
3      0.142857
dtype: float64

以下各项可用于解决该问题:

# 1) works if you're ok with dropping NA
pd.Series([1,pd.NA],dtype='Int8').dropna().astype(int).value_counts(normalize=True)

# 2) works if you're ok with switching to a non-extension datatype such as float
pd.Series([1,pd.NA],dtype='Int8').astype(float).value_counts(normalize=True)

# 3) The issue may be fixed in a future versions of pandas. Try using a pandas version >= 1.1

相关问题 更多 >