将标题转换为行 [英] Convert header into row

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

问题描述

我有一张这样的桌子.

user    01/12/15    02/12/15 someBool
u1      100         300      true
u2      200        -100      false
u3     -50          200      true

我想像这样将日期列重新划分为两列datevalue.

I want to repartition the date columns into two columns date and value like this.

user    date       value   someBool
u1      01/12/15   100     true
u1      02/12/15   300     true
u2      01/12/15   200     false
u2      02/12/15  -100     false
u3      01/12/15   50      true
u3      02/12/15   200     true

如何在python中执行此操作? pandas中的pivot_table有帮助吗?

How to do this in python ? Is pivot_table in pandas helpful?

如果可能,请提供代码/伪代码&提供有关python版本的详细信息.

If possible provide code/psuedo code & give details on python version.

推荐答案

您需要 melt :

df = pd.melt(df, id_vars=['user','someBool'], var_name='date')
print (df)
  user someBool      date  value
0   u1     True  01/12/15    100
1   u2    False  01/12/15    200
2   u3     True  01/12/15    -50
3   u1     True  02/12/15    300
4   u2    False  02/12/15   -100
5   u3     True  02/12/15    200

使用 stack :

df = df.set_index(['user','someBool'])
       .stack()
       .reset_index(name='value')
       .rename(columns={'level_2':'date'})
print (df)
  user someBool      date  value
0   u1     True  01/12/15    100
1   u1     True  02/12/15    300
2   u2    False  01/12/15    200
3   u2    False  02/12/15   -100
4   u3     True  01/12/15    -50
5   u3     True  02/12/15    200

这篇关于将标题转换为行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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