bju*_*trs 23 python transpose dataframe pandas
我有一个csv格式的表,看起来像这样.我想转置表,以便指标名称列中的值是新列,
Indicator Country Year Value
1 Angola 2005 6
2 Angola 2005 13
3 Angola 2005 10
4 Angola 2005 11
5 Angola 2005 5
1 Angola 2006 3
2 Angola 2006 2
3 Angola 2006 7
4 Angola 2006 3
5 Angola 2006 6
Run Code Online (Sandbox Code Playgroud)
我希望最终结果像这样:
Country Year 1 2 3 4 5
Angola 2005 6 13 10 11 5
Angola 2006 3 2 7 3 6
Run Code Online (Sandbox Code Playgroud)
我尝试过使用pandas数据框并没有太大的成功.
print(df.pivot(columns = 'Country', 'Year', 'Indicator', values = 'Value'))
Run Code Online (Sandbox Code Playgroud)
有关如何实现这一点的任何想法?
谢谢
JAB*_*JAB 36
你可以使用pivot_table:
pd.pivot_table(df, values = 'Value', index=['Country','Year'], columns = 'Indicator').reset_index()
Run Code Online (Sandbox Code Playgroud)
这个输出:
Indicator Country Year 1 2 3 4 5
0 Angola 2005 6 13 10 11 5
1 Angola 2006 3 2 7 3 6
Run Code Online (Sandbox Code Playgroud)
小智 9
这是一个猜测:它不是“.csv”文件,而是从“.csv”导入的 Pandas DataFrame。
要透视此表,您需要 Pandas“透视”中的三个参数。例如,如果
df是您的数据框:
table = df.pivot(index='Country',columns='Year',values='Value')
print (table)
Run Code Online (Sandbox Code Playgroud)
这应该会给出所需的输出。
| 归档时间: |
|
| 查看次数: |
40640 次 |
| 最近记录: |