熊猫数据框条件.mean()取决于某列中的值

时间:2015-04-21 16:44:22

标签: python pandas conditional mean

我试图创建一个新列,它返回同一df中现有列的值的平均值。但是,应根据其他三列中的分组计算平均值。

Out[184]: 
   YEAR daytype hourtype  scenario  option_value    
0  2015     SAT     of_h         0      0.134499       
1  2015     SUN     of_h         1     63.019250      
2  2015     WD      of_h         2     52.113516       
3  2015     WD      pk_h         3     43.126513       
4  2015     SAT     of_h         4     56.431392 

我基本上想要一个新专栏' mean'它计算"选项值"的平均值,当" YEAR"," daytype"和" hourtype"很相似。

我尝试了以下方法,但没有成功......

In [185]: o2['premium']=o2.groupby(['YEAR', 'daytype', 'hourtype'])['option_cf'].mean()

TypeError: incompatible index of inserted column with frame index

2 个答案:

答案 0 :(得分:8)

这是一种方法

In [19]: def cust_mean(grp):
   ....:     grp['mean'] = grp['option_value'].mean()
   ....:     return grp
   ....:

In [20]: o2.groupby(['YEAR', 'daytype', 'hourtype']).apply(cust_mean)
Out[20]:
   YEAR daytype hourtype  scenario  option_value       mean
0  2015     SAT     of_h         0      0.134499  28.282946
1  2015     SUN     of_h         1     63.019250  63.019250
2  2015      WD     of_h         2     52.113516  52.113516
3  2015      WD     pk_h         3     43.126513  43.126513
4  2015     SAT     of_h         4     56.431392  28.282946

那么,你的尝试出了什么问题?

它返回一个与原始数据框形状不同的聚合。

In [21]: o2.groupby(['YEAR', 'daytype', 'hourtype'])['option_value'].mean()
Out[21]:
YEAR  daytype  hourtype
2015  SAT      of_h        28.282946
      SUN      of_h        63.019250
      WD       of_h        52.113516
               pk_h        43.126513
Name: option_value, dtype: float64

使用transform

In [1461]: o2['premium'] = (o2.groupby(['YEAR', 'daytype', 'hourtype'])['option_value']
                              .transform('mean'))

In [1462]: o2
Out[1462]:
   YEAR daytype hourtype  scenario  option_value    premium
0  2015     SAT     of_h         0      0.134499  28.282946
1  2015     SUN     of_h         1     63.019250  63.019250
2  2015      WD     of_h         2     52.113516  52.113516
3  2015      WD     pk_h         3     43.126513  43.126513
4  2015     SAT     of_h         4     56.431392  28.282946

答案 1 :(得分:1)

您可以通过以下方式调整代码,按照预期的方式执行此操作:

o2 = o2.set_index(['YEAR', 'daytype', 'hourtype'])

o2['premium'] = o2.groupby(level=['YEAR', 'daytype', 'hourtype'])['option_value'].mean()

为什么原始错误?正如John Galt所解释的那样,来自groupby()。mean()的数据与原始DataFrame的形状(长度)不同。

如果您首先使用'分组列,那么Pandas可以巧妙地处理这个问题。在索引中。然后它知道如何正确传播平均数据。

John的解决方案遵循相同的逻辑,因为groupby在执行期间自然地将分组列放在索引中。

相关问题