Help us understand the problem. What is going on with this article?

pandasの行を列にする

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

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away