How to sum dataframe in pandas for more than 5

Shi*_*nde 4 python sum pandas pandas-groupby

in my days column if my number is more than 5 I want to sum that column

Input:

Days  files 
1      10
3      20
4      30
5      40
6      50
Run Code Online (Sandbox Code Playgroud)

Required output:

Days  files 
1      10
3      20
4      30
5+     90
Run Code Online (Sandbox Code Playgroud)

ank*_*_91 6

您可以尝试series.clip剪辑系列中的上限,然后进行分组和求和:

out = df['files'].groupby(df['Days'].clip(upper=5)).sum().reset_index()
print(out)

  Days  files
0    1     10
1    3     20
2    4     30
3    5     90
Run Code Online (Sandbox Code Playgroud)

如果您真的想将 5 以上的任何内容更改为 str 类型,您可以5使用上述逻辑替换掉:

out = df['files'].groupby(df['Days'].clip(upper=5).replace(5,'5+')).sum().reset_index()
print(out)

  Days  files
0    1     10
1    3     20
2    4     30
3   5+     90
Run Code Online (Sandbox Code Playgroud)