使用两列作为变量的长到宽数据框

时间:2019-03-19 08:00:44

标签: python pandas dataframe reshape

我想使用port1port2作为感兴趣的变量,从长到宽重塑以下数据

            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

顶部的数字与port1port2相似。我不确定使用正确的代码会导致什么结果。

我在使用unstack()port1port2用作索引时曾尝试date,并且尝试使用pivot_table,但是在实现这一目标上并不幸运输出。

任何想法都很棒!

1 个答案:

答案 0 :(得分:2)

首先将各列连接在一起,然后将DataFrame.set_index与参数append=True连接起来,最后将Series.unstack重塑形状:

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
相关问题