草庐IT

Python Pandas : Convert Rows as Column headers

coder 2023-05-22 原文

我有以下数据框:

Year    Country          medal    no of medals
1896    Afghanistan      Gold        5
1896    Afghanistan      Silver      4
1896    Afghanistan      Bronze      3
1896    Algeria          Gold        1
1896    Algeria          Silver      2
1896    Algeria          Bronze      3

我想要这样。

Year    Country      Gold   Silver   Bronze
1896    Afghanistan    5      4         3
1896    Algeria        1      2         3

Stack/Unstack 似乎不起作用。

最佳答案

您正在寻找 pivot_table :

In [11]: medals = df.pivot_table('no of medals', ['Year', 'Country'], 'medal')

In [12]: medals
Out[12]:
medal             Bronze  Gold  Silver
Year Country
1896 Afghanistan       3     5       4
     Algeria           3     1       2

如果你想重新排序列:

In [12]: medals.reindex_axis(['Gold', 'Silver', 'Bronze'], axis=1)
Out[12]:
medal             Gold  Silver  Bronze
Year Country
1896 Afghanistan     5       4       3
     Algeria         1       2       3

关于Python Pandas : Convert Rows as Column headers,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17298313/

有关Python Pandas : Convert Rows as Column headers的更多相关文章

随机推荐