HappyPy HappyPy - 5 months ago 16
Python Question

how to convert column names into column values in pandas - python

df=pd.DataFrame(index=['x','y'], data={'a':[1,2],'b':[3,4]})


how can I convert column names into values of a column? This is my desired output

c1 c2
x 1 a
x 3 b
y 2 a
y 4 b

Answer

You can use:

print (df.T.unstack().reset_index(level=1, name='c1')
                     .rename(columns={'level_1':'c2'})[['c1','c2']])
   c1 c2
x   1  a
x   3  b
y   2  a
y   4  b

Or:

print (df.stack().reset_index(level=1, name='c1')
                 .rename(columns={'level_1':'c2'})[['c1','c2']])
   c1 c2
x   1  a
x   3  b
y   2  a
y   4  b