Skip to main content
 首页 » 编程设计

python之数据框中任意两行之间差异的 Pandas 平均值

2024年10月17日7me-sa

我有一个数据框

name   date         quantity 
'A'    2016-12-02   20 
'A'    2016-12-04   5 
'A'    2016-11-30   10 
'B'    2016-11-30   10 
... 

我想做的是计算一个名字的任意一对 连续 日期(按时间顺序连续)、数量差异以及这些名字的平均值。

日期确实不一定按时间顺序显示。

具体来说,对于名称 A,我想计算 +10(12 月 2 日 - 11 月 30 日的差异)和 -15(12 月 4 日 - 11 月 2 日的差异),然后对它们进行平均,以获得此名称的最终结果为 -2.5。

想法?

请您参考如下方法:

您可以使用 groupby和申请 diff与 mean :

print (df.groupby('name')['quantity'].apply(lambda x: x.diff().mean()).reset_index()) 
  name  quantity 
0  'A'      -2.5 
1  'B'       NaN 

编辑:您可以添加 sort_values按列 date

print (df.sort_values('date') 
         .groupby('name')['quantity'] 
         .apply(lambda x: x.diff().mean()) 
         .reset_index()) 
  name  quantity 
0  'A'      -2.5 
1  'B'       NaN