python - Pandas Dataframe - 在 A 列中的每个标签中查找 B 列中的总和

标签 python pandas multiple-entries

假设我们有以下数据:

...    col1    col2    col3
 0      A      1       info
 1      A      2       other
 2      B      3       blabla

我想使用 python pandas 查找重复条目(在第 1 列中)并根据第 2 列将它们相加。

在 python 中我会做类似下面的事情:

l = [('A',1), ('A',2), ('B',3)]
d = {}
for i in l:
    if(i[0] not in d.keys()):
        d[i[0]]=i[1]
    else:
        d[i[0]]=d[i[0]]+i[1]
print(d)

所以结果是:

{'A': 3, 'B': 3}

有没有一种简单的方法可以使用 pandas 做同样的事情?

最佳答案

使用DataFrame.groupby().sum() :

In [1]: import pandas

In [2]: df = pandas.DataFrame({"col1":["A", "A", "B"], "col2":[1,2,3]})

In [3]: df.groupby("col1").sum()
Out[3]: 
      col2
col1      
A        3
B        3

In [4]: df.groupby("col1").sum().reset_index()
Out[4]: 
  col1  col2
0    A     3
1    B     3

[2 rows x 2 columns]

关于python - Pandas Dataframe - 在 A 列中的每个标签中查找 B 列中的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23346433/

相关文章:

python - 如何使用 OpenCV 在 Python 中查找图像的平均颜色?

python - 对数据框中所有行组合求和的更快方法

RESTful 使用 Jersey : method to POST multiple entities

jquery - 多元素选择的第一个类型

javascript - html-webpack-plugin 多个入口点添加所有脚本

python - 终止长时间运行的 python 线程

python - 在 django 中将 openpyxl 工作簿对象作为 HttpResponse 返回。可能吗?

python - 如何更改 IPython %pdb 和 %debug 调试器?

python - Pandas : Get top n records based on the sum of every top i record for each group

Python:将 Pandas 中的值从一帧写入另一帧不起作用