Python pandas groupby()跳过Datafram中的重复值

2024-06-01 20:05:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个pandas dataframe,我使用groupby()函数按我想要的方式分组,除了pandas跳过重复的值,只显示唯一的值。在

这是一个示例数据帧

data = [ 
    ['American Mathematical Society', 'Journal', 2, 'Mathematics & Statistics'],
    ['American Mathematical Society', 'Journal', 2, 'Mathematics & Statistics'],
    ['American Mathematical Society', 'Journal', 38, 'Mathematics & Statistics'],
    ['American Mathematical Society', 'Journal', 4, 'Mathematics & Statistics']]

df = pd.DataFrame(data, columns = ['Provider', 'Type', 'Downloads JR1 2017', 'Field'])

现在,我使用groupby函数按我喜欢的方式在列表中对它们进行分组。在

^{pr2}$

输出如下:

^{3}$

但是,输出中应该有4个项目。相反,我只有3个。我看到重复的值已经从结果中删除了,因为其中两行在“Downloads JR1 2017”列中的值为“2”。在

为什么?我怎样才能得到所有的结果?在

我希望得到的输出是“提供者”的名称,其总和为“Downloads JR1 2017”。示例:

['American Mathematical Society', 46]

Tags: 函数示例dataframepandasdatadownloads方式journal
2条回答

根据你在评论中附加的细节,怎么样

df.groupby(['Provider', 'Field'], as_index=False).sum()

所以你可以检查transform

jr1_provider = provider_subset.groupby(['Provider', 'Field', 'Downloads JR1 2017'], as_index=False).transform('sum').values.tolist()

相关问题 更多 >