如何在Pandas中透视数据框?

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)

  • 查看输出的第一行(列名称) - 除了从指标列派生的列之外,为什么还有指标列 [左列('`Indicator`')] [右 5 列 (`1`, ` 2`、`3`、`4`、`5`)]? (4认同)

小智 9

这是一个猜测:它不是“.csv”文件,而是从“.csv”导入的 Pandas DataFrame。

要透视此表,您需要 Pandas“透视”中的三个参数。例如,如果 df是您的数据框:

table = df.pivot(index='Country',columns='Year',values='Value')  
print (table)
Run Code Online (Sandbox Code Playgroud)

这应该给出所需的输出。