如何将一列的所有值转换为Pandas DataFrame中的列名 [英] How to convert one column's all values to separate column name in DataFrame of Pandas

查看:5376
本文介绍了如何将一列的所有值转换为Pandas DataFrame中的列名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

样本数据如下:

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

我打算将DataFrame转换为如下:

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!

推荐答案

使用枢纽

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

这篇关于如何将一列的所有值转换为Pandas DataFrame中的列名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆