pandas 根据另一列的唯一值对列的值求和
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/51330281/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sum values of column based on the unique values of another column
提问by user_01
I have a data frame of
我有一个数据框
Column1 Column2
1 20
2 25
3 30
2 40
4 18
1 24
and I want to sum Column2 based on the unique values of Column1. We can find sum based on a specific value such as 1 using this way:
我想根据 Column1 的唯一值对 Column2 求和。我们可以使用这种方式找到基于特定值(例如 1)的总和:
df.loc[df['Column1'] == 1, 'Column2'].sum()
which correctly gives us 44. But how we can do it for all unique values in Column1 such that it produces this one
这正确地给了我们 44。但是我们如何为 Column1 中的所有唯一值执行它,以便它产生这个
Column1 Column2
1 44
2 65
3 30
4 18