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



我很难将agg应用于groupby熊猫数据帧。

我有一个数据帧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的值(的bird_distance来创建新列crow

order_id    distance_theo    bird_distance    crow
10              100               80    1.25
10               80               80    1.25
10               70               80    1.25
11               90               70    1.29
11               70               70    1.29
11               60               70    1.29
12              200              180    1.11
12              150              180    1.11
12              100              180    1.11
12               60              180    1.11

我的尝试:df.groupby('order_id'(.agg({'crow',lambda x:x.distance_theo.head(1(/x.bird_distance.head(1(}(

但我得到了一个错误:

'Series' object has no attribute 'distance_theo'

我该如何解决这个问题?谢谢你的任何建议!

使用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

您可以在没有groupby的情况下使用drop_duplicatejoin:

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

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

df1.join(df1.drop_duplicates('order_id')
.assign(crow=df1.distance_theo / df1.bird_distance)[['crow']]).ffill()

输出:

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

最新更新