长/宽数据到宽/长 [英] Long/wide data to wide/long

查看:92
本文介绍了长/宽数据到宽/长的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框,如下所示:

I have a data frame that look as follow:

import pandas as pd
d = {'decil': ['1. decil','1. decil','2. decil','2. decil','3. decil','3. decil'],
    'kommune': ['AA','BB','AA','BB','AA','BB'],'2010':[44,25,242,423,845,962],
    '2011':[64,26,239,620,862,862]}    
df = pd.DataFrame(data=d)

打印

decil      kommune  2010  2011
1. decil   AA       44    64
1. decil   BB       25    26
2. decil   AA      242   239
2. decil   BB      423   620
3. decil   AA      845   862
3. decil   BB      962   862

我想要的输出是这样的

 kommune  year  1. decil  2. decil  3. decil
 AA       2010        44       242       845
 AA       2011        64       239       862
 BB       2010        25       423       962
 BB       2011        25       620       862

也就是说,我正在寻找一种将'decil'列从长格式更改为宽格式,同时将年列从宽格式更改为长格式的方法.我已经尝试过pd.pivot_table,循环运行并且没有任何运气.有什么聪明的办法解决吗?预先感谢您的帮助.

That is, I'm searching for a way to change the 'decil' column from long to wide format while at the same time changing the year columns from wide to long format. I have tried pd.pivot_table, loops and unstack without any luck. Is there any smart way around this? In advance, thanks for the help.

推荐答案

使用 set_index stack unstack :

Use set_index with stack and unstack:

df = (df.set_index(['decil','kommune'])
        .stack()
        .unstack(0)
        .reset_index()
        .rename_axis(None, axis=1))

print (df)
  kommune level_1  1. decil  2. decil  3. decil
0      AA    2010        44       242       845
1      AA    2011        64       239       862
2      BB    2010        25       423       962
3      BB    2011        26       620       862

这篇关于长/宽数据到宽/长的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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