python - 熊猫数据框总和
问题描述
我有一个看起来像这样的熊猫数据框:
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 中执行此操作?
解决方案
只需在末尾添加一行代码
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
推荐阅读
- python-3.x - TimeoutException:消息:超时和网页未通过 Python3 加载/响应 ChromeDriver Chrome
- xquery - 使用 ModuleExecutor 设置的 CORB 作业
- excel - VBA在excel中嵌套IF
- scala - 当我尝试在 Scala 中运行 John Snow spark-nlp 示例时,我得到“任务不可序列化”
- google-chrome - 为什么我必须在我的证书 SAN 中使用 DNS.1 = localhost 才能让 Chrome 接受它
- c - 如何诊断将缓冲区反序列化为结构的问题?
- powershell - 使用 PowerShell 和基于文件的数据库操作
- python - 当for循环没有运行整个代码时如何修复它
- python - 如何将 f-string 与变量一起使用,而不是与字符串文字一起使用?
- linux - 从管道读取输入时执行问题