简体   繁体   English

pandas:groupby sum 以其他列为条件

[英]pandas: groupby sum conditional on other column

i have a dataframe which looks like this我有一个 dataframe 看起来像这样

pd.DataFrame({'a':['A', 'B', 'B', 'C', 'C', 'D', 'D', 'E'],
              'b':['Y', 'Y', 'N', 'Y', 'Y', 'N', 'N', 'N'],
              'c':[20, 5, 12, 8, 15, 10, 25, 13]})

   a  b   c
0  A  Y  20
1  B  Y   5
2  B  N  12
3  C  Y   8
4  C  Y  15
5  D  N  10
6  D  N  25
7  E  N  13

i would like to groupby column 'a', check if any of column 'b' is 'Y' or True and keep that value and then just sum on 'c'我想按列'a'分组,检查'b'列中的任何一个是否为'Y'或True并保留该值,然后对'c'求和

the resulting dataframe should look like this生成的 dataframe 应如下所示

   a  b   c
0  A  Y  20
1  B  Y  17
2  C  Y  23
3  D  N  35
4  E  N  13

i tried the below but get an error我尝试了以下但得到一个错误

df.groupby('a')['b'].max()['c'].sum()

You can use agg with max and sum .您可以将aggmaxsum一起使用。 Max on column 'b' indeed works because 'Y' > 'N' == True 'b' 列的最大值确实有效,因为 'Y' > 'N' == True

print(df.groupby('a', as_index=False).agg({'b': 'max', 'c': 'sum'}))

   a  b   c
0  A  Y  20
1  B  Y  17
2  C  Y  23
3  D  N  35
4  E  N  13

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

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