Lost1 Lost1 - 2 months ago 10
Python Question

Reshaping a column based on another column in a pandas dataframe

Date Sin Ret
01/01/1990 True 0.03
01/02/1990 True 0.02
01/01/1990 False 0.01
01/02/1990 False 0.05


I would like

Date Ret1 Ret2
01/01/1990 0.03 0.01
01/02/1990 0.02 0.05


so that I can get

Date Ret1-Ret2
01/01/1990 0.02
01/02/1990 -0.03


What is the best way to do this? I was thinking setting Date and sin as index and unstack sin. Is there an easier way?

Answer Source

I think setting index and stacking is a good idea but here is an alternative with pivot:

(df.pivot(index='Date', columns='Sin', values='Ret')
   .rename(columns={True: 'Ret1', False: 'Ret2'}))

Sin         Ret1  Ret2
Date                  
01/01/1990  0.03  0.01
01/02/1990  0.02  0.05