How to convert one column's all values to separate column name in DataFrame of Pandas

自作多情 提交于 2020-03-05 12:22:11

问题


Sample data are as follows:

df = pd.DataFrame([(2011, 'a', 1.3), (2012, 'a', 1.4), (2013, 'a', 1.6), (2011, 'b', 0.7), (2012, 'b', 0.9), (2013, 'b', 1.2),], columns=['year', 'district', 'price'])
df.set_index(['year'], inplace=True)
df.head(n=10)

which could produce data like:

    district    price
year        
2011    a       1.3
2012    a       1.4
2013    a       1.6
2011    b       0.7
2012    b       0.9
2013    b       1.2

What I intend to convert the DataFrame to is as below:

        a       b
year        
2011    1.3     0.7
2012    1.4     0.9
2013    1.6     1.2

Could anyone give me some idea on how to do that? Great thanks!


回答1:


use pivot

In[122]: df.reset_index().pivot('year','district','price')
Out[122]: 
district    a    b
year              
2011      1.3  0.7
2012      1.4  0.9
2013      1.6  1.2


来源:https://stackoverflow.com/questions/39840377/how-to-convert-one-columns-all-values-to-separate-column-name-in-dataframe-of-p

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!