Home > other >  Un-melt a pandas dataframe
Un-melt a pandas dataframe

Time:03-21

Let say I have below dataframe

import pandas as pd
>>> pd.DataFrame({'product_name': ['laptop', 'printer', 'printer',], 'price': [1200, 150, 1200],  'price1': [1250, 130, 12000]})
  product_name  price  price1
0       laptop   1200    1250
1      printer    150     130
2      printer   1200   12000

Now, I want to unmelt above dataframe, and want to create a new dataframe with just 1 row based on selected original columns as below,

enter image description here

Is there any method/function available with pandas to achieve the same?

Any pointer will be very appreciated.

CodePudding user response:

Ironically, df.melt() is perfect for this! :)

new_df = (
    df
    .melt()
    .assign(variable=lambda x: x['variable']   x.groupby('variable').cumcount().add(1).astype(str))
    .set_index('variable')
    .T
    .reset_index(drop=True)
    .rename_axis(None, axis=1)
)

Output:

>>> new_df
  product_name1 product_name2 product_name3 price1 price2 price3 price11 price12 price13
0        laptop       printer       printer   1200    150   1200    1250     130   12000
One-liner in case you want it:
new_df = df.melt().assign(variable=lambda x: x['variable']   x.groupby('variable').cumcount().add(1).astype(str)).set_index('variable').T.reset_index(drop=True).rename_axis(None, axis=1)
  • Related