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?

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.