我有以下数据框:
date, industry, symbol, roc
25-02-2015, Health, abc, 200
25-02-2015, Health, xyz, 150
25-02-2015, Mining, tyr, 45
25-02-2015, Mining, ujk, 70
26-02-2015, Health, abc, 60
26-02-2015, Health, xyz, 310
26-02-2015, Mining, tyr, 65
26-02-2015, Mining, ujk, 23
我需要确定平均“roc”、最大“roc”、最小“roc”以及每个日期+行业存在多少符号。换句话说,我需要按日期和行业分组,然后确定各种平均值、最大值/最小值等。
到目前为止,我正在做以下工作,但似乎非常缓慢且效率低下:
sector_df = primary_df.groupby(['date', 'industry'], sort=True).mean()
tmp_max_df = primary_df.groupby(['date', 'industry'], sort=True).max()
tmp_min_df = primary_df.groupby(['date', 'industry'], sort=True).min()
tmp_count_df = primary_df.groupby(['date', 'industry'], sort=True).count()
sector_df['max_roc'] = tmp_max_df['roc']
sector_df['min_roc'] = tmp_min_df['roc']
sector_df['count'] = tmp_count_df['roc']
sector_df.reset_index(inplace=True)
sector_df.set_index(['date', 'industry'], inplace=True)
上面的代码有效,生成了一个由日期+行业索引的数据框,向我展示了每个日期+行业的最小/最大“roc”是多少,以及每个日期+行业存在多少个符号。
我基本上是多次完成一个完整的 groupby(以确定“roc”的平均值、最大值、最小值和计数)。这非常慢,因为它一遍又一遍地做同样的事情。
有没有办法只做一次组。然后对该对象执行均值、最大值等并将结果分配给 sector_df?
最佳答案
您想使用 agg
执行聚合:
In [72]:
df.groupby(['date','industry']).agg([pd.Series.mean, pd.Series.max, pd.Series.min, pd.Series.count])
Out[72]:
roc
mean max min count
date industry
2015-02-25 Health 175.0 200 150 2
Mining 57.5 70 45 2
2015-02-26 Health 185.0 310 60 2
Mining 44.0 65 23 2
这允许您传递要执行的函数的可迭代(在本例中为列表)。
编辑
要访问单个结果,您需要为每个轴传递一个元组:
In [78]:
gp.loc[('2015-02-25','Health'),('roc','mean')]
Out[78]:
175.0
其中 gp = df.groupby(['date','industry']).agg([pd.Series.mean, pd.Series.max, pd.Series.min, pd.Series.count ])
关于python - pandas groupby的分配结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30568995/