HappyPy
HappyPy

Reputation: 10697

convert index into columns - pandas

df=pd.DataFrame({'c1':[12,45,21,49],'c2':[67,86,28,55]})

I'd like to convert the index into columns

c1            c2
0  1  2  3    0  1  2  3 
12 45 21 49   67 86 28 55

I tried combining stack and unstack but so far without success

Upvotes: 1

Views: 809

Answers (1)

jezrael
jezrael

Reputation: 862621

Use unstack + to_frame + T:

df=pd.DataFrame({'c1':[12,45,21,49],'c2':[67,86,28,55]})
print (df.unstack().to_frame().T)
   c1              c2            
    0   1   2   3   0   1   2   3
0  12  45  21  49  67  86  28  55

Or DataFrame + numpy.ravel + numpy.reshape with MultiIndex.from_product:

mux = pd.MultiIndex.from_product([df.columns, df.index])
print (pd.DataFrame(df.values.ravel().reshape(1, -1), columns=mux))
   c1              c2              c3            
    0   1   2   3   0   1   2   3   0   1   2   3
0  12  67  67  45  86  86  21  28  28  49  55  55

Upvotes: 3

Related Questions