长/宽数据到宽/长

2024-09-30 05:25:58 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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表,没有任何运气的循环和展开。有什么好办法吗?提前,谢谢你的帮助。你知道吗


Tags: 数据方法importdataframepandasdfdataas
1条回答
网友
1楼 · 发布于 2024-09-30 05:25:58

^{}^{}^{}一起使用:

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

相关问题 更多 >

    热门问题