pandas “部分融化"或“群体融化" [英] Pandas 'partial melt' or 'group melt'

查看:118
本文介绍了 pandas “部分融化"或“群体融化"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的DataFrame

I have a DataFrame like this

>>> df = pd.DataFrame([[1,1,2,3,4,5,6],[2,7,8,9,10,11,12]], 
                      columns=['id', 'ax','ay','az','bx','by','bz'])
>>> df
   id  ax  ay  az  bx  by  bz
0   1   1   2   3   4   5   6
1   2   7   8   9  10  11  12

我想将其转换为类似的内容

and I want to transform it into something like this

   id name   x   y   z
0   1    a   1   2   3
1   2    a   7   8   9
2   1    b   4   5   6
3   2    b  10  11  12

这是一个无法解决的问题,但是我不知道通过保持这些组的完整性来融化的任何方法.我知道我可以在原始数据帧上创建投影,然后在concat上创建投影,但是我想知道是否丢失了我的工具带中的一些常见融化技巧.

This is an unpivot / melt problem, but I don't know of any way to melt by keeping these groups intact. I know I can create projections across the original dataframe and then concat those but I'm wondering if I'm missing some common melt tricks from my toolbelt.

推荐答案

Set_index,将列转换为多索引和堆栈,

Set_index, convert columns to multi index and stack,

df = df.set_index('id')
df.columns = [df.columns.str[1], df.columns.str[0]]
new_df = df.stack().reset_index().rename(columns = {'level_1': 'name'})

    id  name    x   y   z
0   1   a       1   2   3
1   1   b       4   5   6
2   2   a       7   8   9
3   2   b       10  11  12

这篇关于 pandas “部分融化"或“群体融化"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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