简体   繁体   中英

Pandas pivoting multiple columns around a single column

Im trying to turn this

    iVWAPBucket  Side  NotionalTraded
0  -10 - -5 bps   Buy        0.079994
1  -2.5 - 0 bps   Buy        0.031706
2   0 - 2.5 bps   Buy        0.138434
3   10 - 25 bps   Buy        0.296976
4   2.5 - 5 bps   Buy        0.078794
5   2.5 - 5 bps  Sell        0.292118
6    5 - 10 bps   Buy        0.081977

into this

    iVWAPBucket     Buy         Sell
0  -10 - -5 bps     0.079994    -    
1  -2.5 - 0 bps     0.031706    -   
2   0 - 2.5 bps     0.138434    -   
3   10 - 25 bps     0.296976    -   
4   2.5 - 5 bps     0.078794    -   
5   2.5 - 5 bps     -           0.292118
6    5 - 10 bps     0.081977    -   

What is the most efficient way of doing this? I can do a single column like this, but can with multiple

primary_breakdown_table.pivot(index=primary_breakdown_table.index, columns='Side')['NotionalTraded']

use pivot_table() as follows:

df2 = df.pivot_table(
    values='NotionalTraded',
    columns=['Side'],
    index=['iVWAPBucket','Side']
    ).reset_index().drop(columns=['Side'])

df2.columns.rename(None, inplace=True)

output

    iVWAPBucket       Buy      Sell
0  -10 - -5 bps  0.079994       NaN
1  -2.5 - 0 bps  0.031706       NaN
2   0 - 2.5 bps  0.138434       NaN
3   10 - 25 bps  0.296976       NaN
4   2.5 - 5 bps  0.078794       NaN
5   2.5 - 5 bps       NaN  0.292118
6    5 - 10 bps  0.081977       NaN

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