Home > OS >  list not supported for Pandas melt var_name
list not supported for Pandas melt var_name

Time:06-03

I have a dataframe that looks like this:

  Country Person    A    B    C
0     USA    Bob  200  300  400
1  Canada  Alice  100  200  300

I'd like to melt the data to pivot just columns A, B, and C so that it looks like this:

  Country Person Label  Count
0     USA    Bob     A    200
1     USA    Bob     B    300
2     USA    Bob     C    400
3  Canada  Alice     A    100
4  Canada  Alice     B    200
5  Canada  Alice     C    300

I was trying to use melt, but it doesn't seem to support a list for var_name

import pandas as pd
df = pd.DataFrame(data=[['USA', 'Bob', 200, 300, 400],
                        ['Canada', 'Alice', 100, 200, 300]],
                  columns=['Country', 'Person', 'A', 'B', 'C'])
df.melt(['Country', 'Person'], var_name=['A', 'B', 'C'], value_name='Count')

CodePudding user response:

Got your issue.

import pandas as pd
df = pd.DataFrame(data=[['USA', 'Bob', 200, 300, 400],
                        ['Canada', 'Alice', 100, 200, 300]],
                  columns=['Country', 'Person', 'A', 'B', 'C'])
df1 = df.melt(['Country', 'Person'], var_name='Label', value_name='Count').sort_values(by=['Country','Person','Label'], ascending=[False,False,True])
print(df1)
  • Related