pandas 按代码拆分列并连接这些数据

pandas colume split by code and concat these data

我是pandas新手

例如我有如下数据框

code time open high low close
 1    2    1    1    1    1
 2    1    1    1    1    1
 2    2    1    1    1    1

  1. 我想按代码拆分列
  2. 我想按时间在索引上连接这些拆分数据并填充 NaN

喜欢下面

                    "1"                  "2"
time(index) open high low close  open high low close
     1      NaN  NaN  NaN  NaN    1     1   1    1
     2       1    1    1    1     1     1   1    1

有什么方法可以使用pandas吗?

使用:


df = df.set_index(['time', 'code']).unstack().swaplevel(0,1,1).sort_index(1)

选择:

df = df.pivot('time', 'code').swaplevel(0,1,1).sort_index(1)

print (df)
code     1                    2               
     close high  low open close high  low open
time                                          
1      NaN  NaN  NaN  NaN   1.0  1.0  1.0  1.0
2      1.0  1.0  1.0  1.0   1.0  1.0  1.0  1.0