6

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.

3
  • 3
    df.set_index(['dir','hour','board_sign'])['pass'].unstack() Commented Nov 2, 2018 at 15:55
  • 2
    Also df.pivot_table(columns='board_sign',index=['dir','hour'],values='pass') Commented Nov 2, 2018 at 16:00
  • thanks!! thats worked exactly as i wanted! Commented Nov 2, 2018 at 16:16

1 Answer 1

4

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
Sign up to request clarification or add additional context in comments.

2 Comments

i tried the pivot_table option at first and it worked. the problem was that i was difficult to use the output because the mulitiindex in the pivot table.
with reset_index() the multiindex is gone

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.