简体   繁体   中英

Reshaping dataframe with multiple columns to row groups

inp Dataframe

df = pd.DataFrame({'Loc': ['Hyd', 'Hyd','Bang','Bang'],
               'Item': ['A', 'B', 'A', 'B'],
               'Month' : ['May','May','June','June'],
               'Sales': [100, 100, 200, 200],
                'Values': [1000, 1000, 2000, 2000]
               })

My expected output

df = pd.DataFrame({'Loc': ['Hyd', 'Hyd','Hyd','Hyd','Bang','Bang','Bang','Bang'],
               'Item': ['A', 'A', 'B', 'B','A', 'A', 'B', 'B'],
               'VAR' : ['Sales','Values','Sales','Values','Sales','Values','Sales','Values'],
               'May': [100, 1000, 100, 1000, 100, 1000, 100, 1000],
                'June': [200, 2000, 200, 2000, 200, 2000, 200, 2000]
               })

I have tried multiple solutions using melt and pivot but nothing seems to work? not sure where I am missing?

Here's my code

    dem.melt(['Part','IBU','Date1']).pivot_table(index=['Part','IBU','variable'],columns=['Date1'])

Any help would be much appreciated

You can use melt and pivot functions in pandas:

df_melted = pd.melt(df, id_vars=["Loc", "Item", "Month"], value_vars=["Sales", "Values"])

This will result:

在此处输入图像描述

And then:

df_pivot = df_melted.pivot_table(index=["Loc", "Item", "variable"], columns="Month")

So, the final output will be:

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM