首页 > 解决方案 > 熊猫数据框总和

问题描述

我有一个看起来像这样的熊猫数据框:

import pandas as pd

ticker = ['YAR.OL', 'DNB.OL', 'TSLA', 'NHY.OL', 'SBO.OL', 'STB.OL']
country = ['Norway', 'Norway', 'United States', 'Norway', 'Norway', 'Norway']
alloc = [11.822, 2.917, 0.355, 74.158, 9.673, 1.075]

dfn = pd.DataFrame(country,columns =['country'])
dfn['Allocation'] = pd.DataFrame(alloc)

在此处输入图像描述

我想总结一下每个国家的分配情况,例如: 挪威:99,645 美国:0,355

如何使用我生成的 df 在 python 中执行此操作?

标签: pythonpandas

解决方案


只需在末尾添加一行代码

dfn=dfn.groupby(['country']).sum()

乍看上去

import pandas as pd

ticker = ['YAR.OL', 'DNB.OL', 'TSLA', 'NHY.OL', 'SBO.OL', 'STB.OL']
country = ['Norway', 'Norway', 'United States', 'Norway', 'Norway', 'Norway']
alloc = [11.822, 2.917, 0.355, 74.158, 9.673, 1.075]

dfn = pd.DataFrame(country,columns =['country'])
dfn['Allocation'] = pd.DataFrame(alloc)
dfn=dfn.groupby(['country']).sum()

print(dfn)

输出:

country           Allocation               
Norway             99.645
United States       0.355

推荐阅读