1

I am new to python and have a need where I need to trasform below pandas dataframe -

type           c1                 c2             c3
 a             9                  10.0          -11.11
 b             162                165.0         -1.85
 c             16                 15.0           6.25

to this format-

      a                  b                 c
c1   c2    c3      c1    c2    c3    c1   c2   c3
9   10.0 -11.11    162  165 -1.85    16  15.0  6.25

I have tried various combinations of transpose, multi-indexing and pivoting but no luck, could you please help me find the solution for this.

Thanks!

2 Answers 2

2

Here's one way:

df1 = df.set_index('type').stack()
df = pd.DataFrame(df1.values.reshape(-1,len(df1)), columns = df1.index)

Alternative:

df = df.set_index('type').stack().to_frame().T

OUTPUT:

type    a                   b                  c            
       c1    c2     c3     c1     c2    c3    c1    c2    c3
0     9.0  10.0 -11.11  162.0  165.0 -1.85  16.0  15.0  6.25
Sign up to request clarification or add additional context in comments.

Comments

1

Try this:

result = (
    df.set_index('type')
      .stack()
      .to_frame()
      .T
)

If you feel overwhelmed by the chain of operations, try one line a time to see its effect:

Step 1:

(
    df.set_index('type')
      .stack()
    # .to_frame()
    # .T
)

Step 2:

(
    df.set_index('type')
      .stack()
      .to_frame()
    # .T
)

And so on...

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.