I have a pandas dataframe. I need to convert some of the columns into rows. The dataframe has same data in the first two columns for every 3 rows. So, I need 6 more columns as you will see in my expected dataframe.
I have the following dataframe:
shopCode Product Code Score
111 Apple 123 0.70
111 Apple 456 0.75
111 Apple 789 0.80
222 Orange 142 0.66
222 Orange 136 0.83
222 Orange 623 0.76
My expected dataframe is:
shopCode Product Code1 Code2 Code3 Score1 Score2 Score3
111 Apple 123 456 789 0.70 0.75 0.80
222 Orange 142 136 623 0.66 0.83 0.76
I tried to use
df.pivot(index=['shopCode', 'Product'], columns=['Code1', 'Code2', 'Code3', 'Score1', 'Score2', 'Score3'], values=['Code', 'Score'])
but it doesn't work.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…