2013-06-25 76 views
24

我有以下數據框:Python的大熊貓:轉換行作爲列標題

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似乎不工作。

回答

35

您正在尋找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 
+7

這就形成了一個多層次的指數,這是不是100%,他有什麼事。通過'medals.reset_index(drop = False,inplace = True)'擺脫它,然後按照'medals.reindex_axis(['Year','Country','Gold','Silver','Bronze'],axis = 1)' – madoki