Pandas melt function using column index positions rather than colum names

3.8k Views Asked by At

Is there a way to set column names for arguments as column index position, rather than column names? Every example that I see is written with column names on value_vars. I need to use the column index.

For instance, instead of:

df2 = pd.melt(df,value_vars=['asset1','asset2'])

Using something similar to:

df2 = pd.melt(df,value_vars=[0,1])
1

There are 1 best solutions below

6
On BEST ANSWER

Select columns names by indexing:

df = pd.DataFrame({
        'asset1':list('acacac'),
         'asset2':[4]*6,
         'A':[7,8,9,4,2,3],
         'D':[1,3,5,7,1,0],
         'E':[5,3,6,9,2,4]
})



df2 = pd.melt(df,
              id_vars=df.columns[[0,1]],
              value_vars=df.columns[[2,3]], 
              var_name= 'c_name', 
              value_name='Value')
print (df2)

   asset1  asset2 c_name  Value
0       a       4      A      7
1       c       4      A      8
2       a       4      A      9
3       c       4      A      4
4       a       4      A      2
5       c       4      A      3
6       a       4      D      1
7       c       4      D      3
8       a       4      D      5
9       c       4      D      7
10      a       4      D      1
11      c       4      D      0