Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

pandas

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
like image 465
HappyPy Avatar asked Jul 07 '16 09:07

HappyPy


2 Answers

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
like image 112
jezrael Avatar answered Sep 26 '22 17:09

jezrael


try this:

In [279]: df.stack().reset_index().set_index('level_0').rename(columns={'level_1':'c2',0:'c1'})
Out[279]:
        c2  c1
level_0
x        a   1
x        b   3
y        a   2
y        b   4
like image 27
MaxU - stop WAR against UA Avatar answered Sep 23 '22 17:09

MaxU - stop WAR against UA