我有一个包含 Date
列的数据框,我按年份对数据进行分组,然后可以计算均值和中位数。但是如何计算众数呢?这是我得到的错误:
>>> np.random.seed(0)
>>> rng = pd.date_range('2010-01-01', periods=10, freq='2M')
>>> df = pd.DataFrame({ 'Date': rng, 'Val': np.random.random_integers(0,100,size=10) })
>>> df
Date Val
0 2010-01-31 44
1 2010-03-31 47
2 2010-05-31 64
3 2010-07-31 67
4 2010-09-30 67
5 2010-11-30 9
6 2011-01-31 83
7 2011-03-31 21
8 2011-05-31 36
9 2011-07-31 87
>>> df.groupby(pd.Grouper(key='Date',freq='A')).mean()
Val
Date
2010-12-31 49.666667
2011-12-31 56.750000
>>> df.groupby(pd.Grouper(key='Date',freq='A')).median()
Val
Date
2010-12-31 55.5
2011-12-31 59.5
>>> df.groupby(pd.Grouper(key='Date',freq='A')).mode()
Traceback (most recent call last):
File "<pyshell#109>", line 1, in <module>
df.groupby(pd.Grouper(key='Date',freq='A')).mode()
File "C:\Python27\lib\site-packages\pandas\core\groupby.py", line 554, in __getattr__
return self._make_wrapper(attr)
File "C:\Python27\lib\site-packages\pandas\core\groupby.py", line 571, in _make_wrapper
raise AttributeError(msg)
AttributeError: Cannot access callable attribute 'mode' of 'DataFrameGroupBy' objects, try using the 'apply' method
最佳答案
- 使用
np.unique
和return_counts
参数。 - 在 counts 数组上使用
argmax
从唯一数组中获取值。 - 使用
np.apply_along_axis
作为自定义函数mode
def mode(a):
u, c = np.unique(a, return_counts=True)
return u[c.argmax()]
df.groupby(pd.Grouper(key='Date',freq='A')).Val.apply(mode)
Date
2010-12-31 67
2011-12-31 21
Freq: A-DEC, Name: Val, dtype: int64
关于python - 计算 DataFrameGroupBy 对象的模式时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41430896/