在groupby之后迭代求和的正确方法是什么

时间:2019-01-26 14:02:28

标签: python pandas group-by

如下图所示,迭代的正确方法是什么?还是将发行者作为单个列表对象?

dl_df.groupby(['Issuer']).sum()

enter image description here

1 个答案:

答案 0 :(得分:2)

简单的$scope.news.push = response.headline; DataFrame.groupby()以及sum()将会成为解决之道。

示例数据框:

reset_index()

最好是:

>>> df
   A   B
0  1  10
1  1  12
2  1  11
3  1  10
4  2  11
5  2  12
6  3  14

另一种解决方法:

按照提到的@jezrael使用>>> df.groupby('A')['B'].sum().reset_index() # df.groupby(['A']).B.sum().reset_index() A B 0 1 43 1 2 23 2 3 14 as_index

False

应用功能:

此处,传递给>>> df.groupby('A', as_index=False)['B'].sum() A B 0 1 43 1 2 23 2 3 14 的函数将DataFrame作为其参数并返回一个DataFrame。 apply将每个组的结果合并到一个新的DataFrame中。

apply

在将需要Series,DataFrames或GroupBy对象的函数链接在一起时,甚至连>>> df.groupby('A')['B'].apply(lambda x: x.sum()).reset_index() A B 0 1 43 1 2 23 2 3 14 都可以使用。

.pipe

另一种方法df.groupby('A')['B'].pipe(lambda x: x.sum()).reset_index() ,首先需要将列表np.sum()转换为numpy数组,然后将['B']函数与sum()一起使用,最后使用apply()

reset_index()

注意:在这里,套用不是一种有效的方法,而是可行的方法,因此我将其保留为后代而不是删除..

我不知道您是否在寻找以下内容:

将值转换为列表格式:

>>> df['B'] = df['B'].apply(np.array)
>>> df.groupby('A')['B'].apply(np.sum).reset_index()
   A   B
0  1  43
1  2  23
2  3  14

OR:

>>> df.groupby(['A'])['B'].sum().values.tolist()
[43, 23, 14]
# df.groupby('A')['B'].agg(np.sum).values.tolist()