简体   繁体   English

如何通过对第三列中的值求和,将前两列中具有相同值的 Pandas Dataframe 的行组合在一起?

[英]How to group together rows of Pandas Dataframe with same values in first 2 columns by summing values in the 3rd column?

I have a dataframe of the form:我有一个 dataframe 的形式:

在此处输入图像描述

For same values of col1 and col2 (for example, AB), I want to add all values in the col3 of the dataframe such that only one row of that form (AB) remains and all values in col3 correspond to those are added.对于 col1 和 col2 的相同值(例如 AB),我想在 dataframe 的 col3 中添加所有值,以便只保留该表单 (AB) 的一行,并且 col3 中的所有值对应于添加的值。

The result would look like:结果将如下所示:

在此处输入图像描述

I tried:我试过了:

 df.groupby(['col1', 'col2'], axis=0, as_index=True).sum()

but it gave me:但它给了我:

在此处输入图像描述

which is not exactly what I am looking for.这不正是我要找的。 Please help and advise.请帮助和建议。 Thanks in advance.提前致谢。

You just need to do this, False instead of True :你只需要这样做, False而不是True

df.groupby(['col1', 'col2'], axis=0, as_index=False).sum()

暂无
暂无

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

相关问题 比较来自相同 pandas dataframe 的 2 列的值和基于比较的第 3 列的返回值 - comparing values of 2 columns from same pandas dataframe & returning value of 3rd column based on comparison Pandas DataFrame - 按多列值对行求和 - Pandas DataFrame - summing rows by multiple column values 通过过滤 Pandas 中的其他 2 列,在第 3 列中获取唯一值 - get unique values in a 3rd column by filtering 2 other columns in Pandas 熊猫按两列分组,并从第三列输出值 - Pandas groupby two columns and output values from 3rd column 如何将一列中的值传播到其他列中的行(熊猫数据框) - How to propagate values in one column to rows in other columns (pandas dataframe) 在Pandas数据框中查找具有相同列值的行 - Finding rows with same column values in pandas dataframe Pandas:如果来自第三列的字符串值,则根据另一列的值创建列 - Pandas : Create columns based on values of another column if string value from 3rd column Python 比较 2 列并用第 3 列中的值写入第 4 列(熊猫) - Python Compare 2 Columns And Write A 4th Column With Values From 3rd Column (pandas ) 在Pandas DataFrame中比较2列并填充第3列 - Comparing 2 columns in Pandas DataFrame and populating a 3rd column 如何更改特定列的特定行的值,以及 Pandas 中同一数据框中特定行的值 - how to change the values of specific rows for specifc columns, with the values of specific rows in the same dataframe in pandas
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM