Pandas value_counts(normalize=True)
在使用扩展数据类型时会失败。例如,当创建一个包含pd.NA
的int8
系列时,通常会使用Int8
扩展数据类型,但会出现错误:AttributeError: 'IntegerArray' object has no attribute 'sum'
。有什么解决方法吗?
pd.Series([1,pd.NA],dtype='Int8').value_counts(normalize=True)
Pandas value_counts(normalize=True)
在使用扩展数据类型时会失败。例如,当创建一个包含pd.NA
的int8
系列时,通常会使用Int8
扩展数据类型,但会出现错误:AttributeError: 'IntegerArray' object has no attribute 'sum'
。有什么解决方法吗?
pd.Series([1,pd.NA],dtype='Int8').value_counts(normalize=True)
据信这是一个回归错误,参见GH33317。好消息是这在Pandas 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