I have the DataFrame df1 and want its indexes to become the second header.
data1 = [['a', 'b', 'c'], [1, 2, 3], [1, 0, 0], [0, 1, 0]]
columns1 = ['c0', 'c1', 'c2']
index1 = ['i0', 'i1', 'i2', 'i3']
df1 = pd.DataFrame(data1, columns=columns1, index=index1)
print(df1)
c0 c1 c2
i0 a b c
i1 1 2 3
i2 1 0 0
i3 0 1 0
Here is the DataFrame df2 that I want
data2 = [['a', 'b', 'c', 1, 2, 3, 1, 0, 0, 0, 1, 0]]
columns2 = [['c0', 'c1', 'c2', 'c0', 'c1', 'c2', 'c0', 'c1', 'c2', 'c0', 'c1', 'c2'],
['i0', 'i0', 'i0', 'i1', 'i1', 'i1', 'i2',' i2', 'i2', 'i3', 'i3', 'i3']]
df2 = pd.DataFrame(data2, columns=columns2)
print(df2)
c0 c1 c2 c0 c1 c2 c0 c1 c2 c0 c1 c2
i0 i0 i0 i1 i1 i1 i2 i2 i2 i3 i3 i3
0 a b c 1 2 3 1 0 0 0 1 0
CodePudding user response:
You can do:
df1.stack().to_frame().swaplevel(0,1).T
Output:
c0 c1 c2 c0 c1 c2 c0 c1 c2 c0 c1 c2
i0 i0 i0 i1 i1 i1 i2 i2 i2 i3 i3 i3
0 a b c 1 2 3 1 0 0 0 1 0