简体   繁体   中英

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?

Here's a solution with df.set_index and df.unstack :

In [516]: df.set_index(['Date', 'Sin']).unstack(0).diff().iloc[-1]
Out[516]: 
     Date      
Ret  01/01/1990    0.02
     01/02/1990   -0.03
Name: True, dtype: float64

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

My solution only target the final output.

df.Sin=df.Sin.astype(int).replace({0:-1})
df.Ret=df.Sin.mul(df.Ret)
df.groupby('Date')['Ret'].agg({'Ret1-Ret2':'sum'})
            Ret1-Ret2
Date                 
01/01/1990       0.02
01/02/1990      -0.03

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM