1

I have a DataFrame that looks like this:

A B
x 1 2
y 2 4
z 3 6

What I want is:

A_x A_y A_z B_x B_y B_z
1 2 3 2 4 6

Is there a method in Python that allows me to do this? I tried pivot but I don't have an index - I only need one row.

2 Answers 2

4

Here is a simple way, using unstack and reworking the columns:

df2 = df.unstack().to_frame().T
df2.columns = df2.columns.map('_'.join)

output:

   A_x  A_y  A_z  B_x  B_y  B_z
0    1    2    3    2    4    6
Sign up to request clarification or add additional context in comments.

Comments

3

Since @mozway had my exact answer here a different way:

df.unstack().to_frame().T.set_axis(
    ["_".join([a, b]) for a, b in pd.MultiIndex.from_product([df.columns, df.index])],
    axis=1,
)

Try:

dfi = df.unstack().to_frame().T
dfi.columns = dfi.columns.map('_'.join)
dfi

Output:

   A_x  A_y  A_z  B_x  B_y  B_z
0    1    2    3    2    4    6

1 Comment

:D we got synchronized!

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.