Jason Zhu Jason Zhu - 2 months ago 7
Python Question

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

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!

Answer

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