I'm pandas newbie
for example I have dataframe as below
code time open high low close
1 2 1 1 1 1
2 1 1 1 1 1
2 2 1 1 1 1
and
like below
"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
is there any way using pandas?
Use:
set_index
+ unstack
or pivot
MultiIndex
in columns by swaplevel
sort_index
df = df.set_index(['time', 'code']).unstack().swaplevel(0,1,1).sort_index(1)
Alternative:
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