如何将列传递到新数据框中的行? [英] How to pass columns to rows in the new dataframe?

查看:49
本文介绍了如何将列传递到新数据框中的行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要基于df创建一个新的数据框new:

I need to create a new dataframe new based on df:

df = 
ID   GROUP_1   GROUP_2    GROUP_3   COUNT   NAME
1    AAA       AAA        CCC       5       xxx
2    BBB       CCC        AAA       6       yyy

结果应该是这个:

new =
ID   GROUP  COUNT  NAME
1    AAA    5      xxx
1    CCC    5      xxx
2    BBB    6      yyy
2    CCC    6      yyy
2    AAA    6      yyy

因此,我想将GROUP_1GROUP_2GROUP_3的值传递到行中(实际上,我有更多以GROUP_开头的列,这就是为什么我更喜欢使用df.filter(regex = "^GROUP") ).

So, I want to pass into row the values of GROUP_1, GROUP_2 and GROUP_3 (in reality I have much more columns starting with GROUP_, that's why I'd prefer to use df.filter(regex = "^GROUP")).

考虑到数据集很大(大约1Gb),我该怎么做?

How can I do this considering that the dataset is quite big (around 1Gb)?

推荐答案

方法1
使用pd.melt

method 1
use pd.melt

cols = ['ID', 'GROUP', 'COUNT', 'NAME']
pd.melt(
    df, ['ID', 'COUNT', 'NAME'],
    ['GROUP_1', 'GROUP_2', 'GROUP_3'],
    value_name='GROUP')[cols]

方法2
set_index + stack

method 2
set_index + stack

cols = ['ID', 'GROUP', 'COUNT', 'NAME']
df.set_index(['ID', 'COUNT', 'NAME']).stack().reset_index(name='GROUP')[cols]


   ID GROUP  COUNT NAME
0   1   AAA      5  xxx
1   1   AAA      5  xxx
2   1   CCC      5  xxx
3   2   BBB      6  yyy
4   2   CCC      6  yyy
5   2   AAA      6  yyy

这篇关于如何将列传递到新数据框中的行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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