Search code examples
pythonpandaspivottransposemelt

Pandas: pivoting rows to columns with columns as column-row


I have a data frame that looks like this

df = pd.DataFrame({'A': [1,2,3], 'B': [11,12,13]})
df

    A   B
0   1   11
1   2   12
2   3   13

I would like to create the following data frame where the columns are a combination of each column-row

    A0  A1  A2  B0  B1  B2
0   1   2   3   11  12  13

It seems that the pivot and transpose functions will switch columns and rows but I actually want to flatten the data frame to a single row. How can I achieve this?


Solution

  • IIUC

    s=df.stack().sort_index(level=1).to_frame(0).T
    s.columns=s.columns.map('{0[1]}{0[0]}'.format) 
    s
       A0  A1  A2  B0  B1  B2
    0   1   2   3  11  12  13