简体   繁体   English

如何在熊猫中分组和转换

[英]How to groupby and transform in pandas

I have dataframe below我有下面的数据框

A B C
1 1 a
1 2 b       
1 3 c
2 4 d
2 5 e

I would ilke to transform like below我想像下面这样变换

A B C
1 6 a
2 9 d

B means the sum of group and C is the first elements in previous df B 表示组和 C 是前一个 df 中的第一个元素

How can I get this result ?我怎样才能得到这个结果?

It seems you need groupby with aggregation - sum and first :看来您需要groupbyaggregation - sumfirst

df = df.groupby('A').agg({'B':'sum','C':'first'}).reset_index().reindex(columns=df.columns)
print (df)
   A  B  C
0  1  6  a
1  2  9  d

Thank you John Galt for another solution:感谢John Galt的另一个解决方案:

df = df.groupby('A', as_index=False).agg({'B':'sum','C':'first'}).reindex(columns=df.columns)
print (df)
   A  B  C
0  1  6  a
1  2  9  d

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM