Skip to content Skip to sidebar Skip to footer

How To Pass Columns To Rows In The New Dataframe?

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 A

Solution 1:

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]

method 2set_index + stack

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

   ID GROUP  COUNT NAME
01   AAA      5  xxx
11   AAA      5  xxx
21   CCC      5  xxx
32   BBB      6  yyy
42   CCC      6  yyy
52   AAA      6  yyy

Post a Comment for "How To Pass Columns To Rows In The New Dataframe?"