Reputation: 1357
I have the first data frame and I would like to convert it as the desirable data frame. I have seen similar questions such as this but mine is a bit more complicated.
# My data frame
F,A,B,C,D,E
---------
Fo,1,2,3,4,5
Foo,6,7,8,9,10
Fooo,11,12,13,14,15
# my desirable data frame
A_Fo,B_Fo,C_Fo,D_Fo,E_Fo,A_Foo,B_Foo,C_Foo,D_Foo,E_Foo,A_Fooo,B_Fooo,C_Fooo,D_Fooo,E_Fooo
--------------------------
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15
Upvotes: 1
Views: 134
Reputation: 1624
Let us try this:
stacked = df.stack()
new_idx = list()
for l in stacked.index.levels[1]:
for f in stacked.index.levels[0]:
new_idx.append(l + '_' + f)
stacked.reset_index(drop=True, inplace=True)
stacked.index = new_idx
print(stacked.to_frame())
Output:
A_fo A_foo A_fooo B_fo B_foo B_fooo C_fo C_foo C_fooo D_fo D_foo D_fooo E_fo E_foo E_fooo
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Upvotes: 1