python - 计算 DataFrameGroupBy 对象的模式时出错

标签 python pandas

我有一个包含 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.uniquereturn_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/

相关文章:

Python - 系列对象是可变的 - 地址解析

python-2.7 - 在Python中读取csv文件?

python - 如何通过 2x2 平均内核对 Pandas 数据帧进行下采样

python - 全局变量搞乱了我的递归函数

python - DataFrame基于多列应用函数,也为多列设置值

python - 重新采样 MultiIndexed Pandas DataFrame 并将不同的函数应用于列

python - 使用无效字符(重音符号)将 CSV 文件读入 Pandas Dataframe

python pandas 自定义权重

python - 如何在sklearn中获得isolationforest的最高预测

javascript - 如何在 Python 中使用 Javascript +Date() 数字时间戳?