2016-10-03 11 views
0

采样数据如下:如何转换一列中的数值全部在大熊猫的数据帧分隔列名

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) 

这可能产生这样的数据:

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 

我打算转换什么数据帧如下:

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

任何人都可以给我一些想法如何做到这一点?万分感谢!

回答

0

使用旋转

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 
+0

谢谢兄弟,是真的有帮助! – KAs