1

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

  1. I want column split by code
  2. I want concat these splited data on index by time and fill NaN

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?

이승훈
  • 350
  • 3
  • 8

1 Answers1

1

Use:


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
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252