Pandas:groupby并创建一个新列,将聚合应用于两个列

2024-10-01 02:33:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我很难将agg应用到groupbypandas数据帧。在

我有一个数据帧df,如下所示:

order_id    distance_theo    bird_distance 
      10              100               80
      10               80               80
      10               70               80
      11               90               70
      11               70               70
      11               60               70
      12              200              180
      12              150              180
      12              100              180
      12               60              180

我想按order_id分组,通过将每组第一行的distance_theo除以每组第一行中的bird_distance得到一个新的列crow(因为一个组中只有一个值bird_distance)。在

^{pr2}$

我的尝试: 数据框groupby('order_id').agg({'crow',lambda x:x.distance)_西奥·海德(1) /x.伯德_距离.头部(1) })

但我得到一个错误:

'Series' object has no attribute 'distance_theo'

我怎么解决这个问题?谢谢你的任何建议!在


Tags: 数据lambdaid距离dfordertheoagg
2条回答

您可以不使用groupby并使用drop_duplicate和{}:

df.join(df.drop_duplicates('order_id')\
  .eval('crow = distance_theo / bird_distance')[['crow']]).ffill()

或者使用assign而不是{}根据@jezraela下面的评论:

^{pr2}$

输出:

   order_id  distance_theo  bird_distance      crow
0        10            100             80  1.250000
1        10             80             80  1.250000
2        10             70             80  1.250000
3        11             90             70  1.285714
4        11             70             70  1.285714
5        11             60             70  1.285714
6        12            200            180  1.111111
7        12            150            180  1.111111
8        12            100            180  1.111111
9        12             60            180  1.111111

groupbyfirst一起使用:

s = df.groupby('order_id').transform('first')
df.assign(crow=s.distance_theo.div(s.bird_distance))

   order_id  distance_theo  bird_distance      crow
0        10            100             80  1.250000
1        10             80             80  1.250000
2        10             70             80  1.250000
3        11             90             70  1.285714
4        11             70             70  1.285714
5        11             60             70  1.285714
6        12            200            180  1.111111
7        12            150            180  1.111111
8        12            100            180  1.111111
9        12             60            180  1.111111

相关问题 更多 >