Use pandas dataframe column values to pivot other columns

Viewed 1981

I have the following dataframe which I want to reshape:

  dir  hour  board_sign  pass
   1    5      d          294
   1    5      u          342
   1    6      d          1368
   1    6      u          1268
   1    7      d          3880
   1    7      u          3817

What I want to do is to use the values from "board_sign" as new columns which will include the values from "pass" column so that the dataframe will look as this:

  dir   hour     d     u
  1      5     294    342
  1      6     1368   1268
  1      7     3880   3817

I already tried several functions as melt pivot stack and unstack but it seems non of them give the wanted result, I also tried the pivot_table but it make is difficult to iterate since the multi index.

It's seems like an easy operation but I just cant get it right. Is there any other function I can use for this?

Thanks.

1 Answers

Use pivot_table:

df = df.pivot_table(index=['dir', 'hour'], columns='board_sign', values='pass').reset_index()
del df.columns.name

df
    dir hour    d   u
0   1     5   294   342
1   1     6   1368  1268
2   1     7   3880  3817
Related