简体   繁体   中英

Set dataframe row as second header

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM