加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 长/宽数据到宽/长

发布时间:2020-12-16 23:34:43 所属栏目:Python 来源:网络整理
导读:我有一个数据框,如下所示: import pandas as pdd = {'decil': ['1. decil','1. decil','2. decil','3. decil','3. decil'],'kommune': ['AA','BB','AA','BB'],'2010':[44,25,242,423,845,962],'2011':[64,26,239,620,862,862]} df = pd.DataFrame(data=d)
我有一个数据框,如下所示:
import pandas as pd
d = {'decil': ['1. decil','1. decil','2. decil','3. decil','3. decil'],'kommune': ['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,循环和unstack没有任何运气.这有什么聪明的方法吗?提前,谢谢你的帮助.

解决方法

使用 set_indexstackunstack
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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读