-1

I'm looking to pivot a dataframe but keep two columns as identifiers (each row of the dataframe will have unique values for each identifier). I can't work out how to do this through the pd.pivot function The original dataframe is:

  name  code colour  price
0   B1   200    red     54
1   B2   201   blue     33
2   B3   202  green     45

and I want to see

 name code red blue green  
 B1   200  54
 B2   201      33
 B3   202           45

1 Answers1

0

How about you use double index?

df = pd.pivot_table(df,values='price',index=['name','code'],columns='colour')
print(df)

Output:

colour     blue  green   red
name code                   
B1   200    NaN    NaN  54.0
B2   201   33.0    NaN   NaN
B3   202    NaN   45.0   NaN

If you wish to have these values as columns then you can simply reset_index().

colour name  code  blue  green   red
0        B1   200   NaN    NaN  54.0
1        B2   201  33.0    NaN   NaN
2        B3   202   NaN   45.0   NaN
Celius Stingher
  • 17,835
  • 6
  • 23
  • 53