LoginSignup
2
1

More than 5 years have passed since last update.

pandasの行を列にする

Posted at

multi indexのcolumn版をやる。

便利なmulti indexの記事

image.png

image.png

こうしたい
つまりclassをtop levelの列にしたい!

以下のようにすればいい

df = pd.DataFrame({
    'class' : ['A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'B'],
    'number' : [1,2,3,4,5,1,2,3,4,5],
    'math' : [90, 20, 50, 30, 57, 67, 89, 79, 45, 23],
    'english' : [40, 21, 68, 89, 90, 87, 89, 54, 21, 23]
})

pipod_df = df.set_index(['number','class']).unstack(level=-1).swaplevel(0,1,axis=1).sort_index(axis=1, level=0)

解説

  • set_index: listを引数に取ることでmulti index化(行名をtupleで取る)
  • unstack: 行を列へ (-1を指定してclassを列に)
  • swaplevel: 列を入れ替える((math, english)⇔class)
  • sort_index: 行を入れ替える

列を指定

pipod_df.loc[:, 'A']

image.png

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1