1

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?

finstats
  • 1,349
  • 4
  • 19
  • 31

2 Answers2

3

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
BENY
  • 317,841
  • 20
  • 164
  • 234
0

One option, with pivot_wider:

# pip install pyjanitor
import janitor
import pandas as pd

df.index = [0] * len(df)
df = df.assign(num=range(len(df)))
df.pivot_wider(names_from="num", names_sep = "")

   A0  A1  A2  B0  B1  B2
0   1   2   3  11  12  13
sammywemmy
  • 27,093
  • 4
  • 17
  • 31