pandas :groupby并创建一个新的列,将聚合应用于两个列 [英] Pandas: groupby and make a new column applying aggregate to two columns
问题描述
我很难将 agg
应用于 groupby
熊猫数据框。
I'm having a difficulty with applying agg
to a groupby
pandas dataframe.
我有一个数据框 df
像这样:
I have a dataframe df
like this:
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
分组,并通过除<$ c $来创建新列 crow
每个组第一行的c> distance_theo ,每组第一行(或任何行中的 bird_distance
),因为只有一组中的一个值 bird_distance
)。
I want to groupby order_id
, and make a new column crow
by dividing distance_theo
of the first row in each group by bird_distance
in the first row of each group(or in any row, because there is only one value of bird_distance
in one group).
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)})
My attempt: 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'
我该如何解决这个?谢谢您提供任何建议!
How can I solve this? Thanks for any kinds of advice!
推荐答案
使用 groupby
和 first
:
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
这篇关于 pandas :groupby并创建一个新的列,将聚合应用于两个列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!