python - 将 pandas 中的数据框从迭代列表转换为适当的列和行
问题描述
我有一个看起来像的数据框
Country | IndicatorName | Value
Spain | Indicator1 | 3
Spain | Indicator2 | 4
Germany | Indicator16 | 24
......
我想将其转换为具有 IndicatorName 列、Country 行和 Value 交叉点的数据框
Country | Indicator 1 | Indicator 2 | Indicator 3 | ......
Spain | 3 | 4 | 16 | ......
Germany | 23 | 232 | 232 | ......
.......
我正在尝试通过 groupby(["IndicatorName","Value"]) 但不确定如何继续
import pandas as pd
indicators = pd.read_csv("Indicators.csv")
indicators.groupbby(["IndicatorName","Value"])
.....
是否有适当的方法来处理这个问题,还是需要通过迭代来完成?
解决方案
我不确定初始 df 格式,因为所需的 df 似乎具有不同的值。
下面的有用吗?
df = pd.DataFrame({'Country' : ['Spain', 'Spain', 'Germany'],
'IndicatorName':['Indicator1', 'Indicator2', 'Indicator16'],
'Value':[3, 4, 24]
})
df.pivot(index = 'Country', columns='IndicatorName', values='Value').fillna(0)
IndicatorName Indicator1 Indicator16 Indicator2
Country
Germany 0.0 24.0 0.0
Spain 3.0 0.0 4.0
推荐阅读
- python - Folium heatmapwithtime empty
- node.js - Webpack 配置入口对象中key-value(array)的含义&作用
- protractor - 失败:无法读取未定义的属性“isDisplayed”
- android - cardview with bottom border
- php - 使用没有 Apache 的 PHP 服务器时解析没有文件扩展名的 url
- php - 小部件未显示在 WP 面板中
- sql-server - SSIS:使用 SQLStatement 输出记录作为完整结果集来输入每个循环容器
- python - 作为我提交给 Slurm 的一部分,如何激活特定的 Python 环境?
- c# - 无法隐式转换类型'System.Tuple
' 到 'System.Collections.Generic.List >' - scala - 为密集 IO 操作优化 cassandra java/scala 驱动程序的配置?