[英]pandas: how to get the sum of rows by grouping inside a DataFrame?
I am new to Data Science and I am currently using the Pandas library on the Jupyter notebook.我是数据科学新手,目前正在 Jupyter 笔记本上使用 Pandas 库。 Sorry for my poor English.对不起我的英语不好。
A,1,5,9
B,2,6,3
A,3,7,2
B,4,8,1
How to group the above CSV values also adding the contents after creating the DataFrame?如何在创建 DataFrame 后将上述 CSV 值分组并添加内容? I want the output something like this.我想要这样的 output 。
A B
0 4 6
1 12 14
2 11 4
Thanks in advance:)提前致谢:)
You can use df.pivot_table
您可以使用df.pivot_table
df
0 1 2 3
0 A 1 5 9
1 B 2 6 3
2 A 3 7 2
3 B 4 8 1
df.pivot_table(columns=0,aggfunc='sum').rename_axis(columns=None)
A B
1 4 6
2 12 14
3 11 4
This is groupby + sum with transpose:这是带有转置的 groupby + sum:
print(df.groupby(0).sum().T.rename_axis(columns=None))
A B
1 4 6
2 12 14
3 11 4
Note: replace 0 in df.groupby(0)
with the actual column name of the first column注意:将df.groupby(0)
中的 0 替换为第一列的实际列名
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.