在 pandas 中使用列名作为新属性 [英] Using column name as a new attribute in pandas

查看:63
本文介绍了在 pandas 中使用列名作为新属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下数据结构

Date         Agric  Food 
01/01/1990    1.3   0.9  
01/02/1990    1.2   0.9 

我想将其隐藏为格式

Date        Sector  Beta
01/01/1990  Agric   1.3
01/02/1990  Agric   1.2
01/01/1990  Food    0.9
01/02/1990  Food    0.9

虽然我确定我可以用一种复杂的方式做到这一点,但是有几行代码可以做到这一点吗?

while I am sure I can do this in a complicated way, is there a way of doing this in a few line of code?

推荐答案

使用 pd.DataFrame.melt

df.melt('Date', var_name='Sector', value_name='Beta')

         Date Sector  Beta
0  01/01/1990  Agric   1.3
1  01/02/1990  Agric   1.2
2  01/01/1990   Food   0.9
3  01/02/1990   Food   0.9

这篇关于在 pandas 中使用列名作为新属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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