Python 使用两列作为变量从长到宽的数据帧

Python 使用两列作为变量从长到宽的数据帧,python,pandas,dataframe,reshape,Python,Pandas,Dataframe,Reshape,我想使用port1和port2作为感兴趣的变量,从长到宽对以下数据进行重塑 port1 port2 w_ret date 2006-01-01 0.0 0.0 0.067991 2006-01-01 0.0 1.0 0.033219 2006-01-01 1.0 0.0 0.073324 2006-01-01 1.0 1.0 0.039730 20

我想使用
port1
port2
作为感兴趣的变量,从长到宽对以下数据进行重塑

            port1  port2     w_ret
date                              
2006-01-01    0.0    0.0  0.067991
2006-01-01    0.0    1.0  0.033219
2006-01-01    1.0    0.0  0.073324
2006-01-01    1.0    1.0  0.039730
2006-01-02    0.0    0.0  0.033616
2006-01-02    0.0    1.0  0.022452
2006-01-02    1.0    0.0 -0.024854
2006-01-02    1.0    1.0  0.020411
我希望重新排列的数据如下所示:

             0.00.0     0.01.0    1.00.0    1.01.0     

date
2006-01-01  0.067991   0.033219  0.073324  0.039730   
2006-01-02  0.033616   0.022452 -0.024854  0.020411
顶部的数字类似于
port1
port2
数字。我不确定如果使用正确的代码,最终会发生什么

我尝试了
unstack()


任何想法都会很棒

首先将列连接在一起,然后使用参数
append=True
,最后通过以下方式重塑形状:


这很聪明D
s = df['port1'].astype(str) + df['port2'].astype(str)
df = df.set_index(s, append=True)['w_ret'].unstack()
print (df)
              0.00.0    0.01.0    1.00.0    1.01.0
date                                              
2006-01-01  0.067991  0.033219  0.073324  0.039730
2006-01-02  0.033616  0.022452 -0.024854  0.020411