3

I would like to reshape the folowing dataframe

enter image description here

into

enter image description here

Could somebody help me with that?

2
  • You may want to try pandas pivot function as explained here Commented Jun 12, 2022 at 13:28
  • 1
    Does this answer your question? Pandas converting Rows to Columns Commented Jun 12, 2022 at 13:56

2 Answers 2

1

Have you tried df.pivot() or pd.pivot()? The values in column C will become column headers. After that, flatten the multi-index columns, and rename them.

import pandas as pd

#df = df.pivot(['A', 'B'], columns='C').reset_index()    #this also works
df = pd.pivot(data=df, index=['A', 'B'], columns='C').reset_index()
df.columns = ['A', 'B', 'X', 'Y']
print(df)

Output

   A   B  X  Y
0  a  aa  1  5
1  b  bb  6  2
2  c  cc  3  7
3  d  dd  8  4

Sometimes, there might be repeated records with the same index, then you'd have to use pd.pivot_table() instead. The param aggfunc=np.mean will take the mean of these repeated records, and become type float as you can see from the output.

import pandas as pd
import numpy as np

df = pd.pivot_table(data=df, index=['A', 'B'], columns='C', aggfunc=np.mean).reset_index()
df.columns = ['A', 'B', 'X', 'Y']
print(df)

Output

   A   B    X    Y
0  a  aa  1.0  5.0
1  b  bb  6.0  2.0
2  c  cc  3.0  7.0
3  d  dd  8.0  4.0
Sign up to request clarification or add additional context in comments.

1 Comment

hi would you help to validate my answer please?
0

You can try

out = df.pivot(index=['A', 'B'], columns='C', values='D').reset_index()
print(out)

C  A   B  X  Y
0  a  aa  1  5
1  b  bb  6  2
2  c  cc  3  7
3  d  dd  8  4

2 Comments

Thank you for your answer. That results in the following error: *** ValueError: Length of passed values is 4, index implies. Any chance you know how to solve this?
@Beertje Do you have a multi index dataframe?

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.