0

(Please help me to rephrase the title. I looked at questions with similar titles but they are not asking the same thing.)

I have a dataframe like this:

        A       B       C
0       1       4       7   
1       2       5       8   
2       3       6       9   

(the first column is indexes and not important)

I need to transform it so it ends up like this:

A    A-1    A-2    B    B-1    B-2    C    C-1    C-2
1    2      3      4    5      6      7    8      9

I know about DataFrame.T which seems one step in the right direction, but how to programatically change the column headers, and move the rows "besides each other" to make it a single row?

Anonymous Entity
  • 3,254
  • 3
  • 27
  • 41

1 Answers1

1

First use DataFrame.unstack with convert values to one columns DataFrame by Series.to_frame and transpose, last flatten MultiIndex in list comprehension with if-else for expected ouput:

df1 = df.unstack().to_frame().T
df1.columns = [a if b == 0 else f'{a}-{b}' for a, b in df1.columns]
print (df1)
   A  A-1  A-2  B  B-1  B-2  C  C-1  C-2
0  1    2    3  4    5    6  7    8    9
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252