32
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

indexからcolumnへ、columnからindexへ

Last updated at Posted at 2017-12-14

SQLで作成したテーブルと、pythonpandasのdataframeを行き来する場合、
pandasindexが登場するとどうも頭がこんがらがってしまう性格なので(滝汗)、
indexの生成、indexの内容をカラムに持たせる部分のメモ。

まずは簡単なdataframeを作ってみる(準備)

import pandas as pd

df = \
pd.DataFrame({ 'date' : ['2017-12-14','2017-12-15','2017-12-16'],
               'symbol' : ["A","B","C"],
               'number' : [1,2,3]})

すると、

>>> df
         date  number symbol
0  2017-12-14       1      A
1  2017-12-15       2      B
2  2017-12-16       3      C

>>> df.index
RangeIndex(start=0, stop=3, step=1)

>>> df.columns
Index([u'date', u'number', u'symbol'], dtype='object')

という感じですね。

カラム内容をindexに持たせる

set_index()の引数に、indexに持たせるカラムを指定します。

## "date"カラムの内容をindexに指定
df1 = df.set_index("date")

>>> df1
            number symbol
date
2017-12-14       1      A
2017-12-15       2      B
2017-12-16       3      C

>>> df1.index
Index([u'2017-12-14', u'2017-12-15', u'2017-12-16'], dtype='object', name=u'date')

>>> df1.columns
Index([u'number', u'symbol'], dtype='object')

indexの内容をカラムに持たせる

reset_index()メソッドで、indexの内容をカラムに戻します。

df2 = df1.reset_index()

>>> df2
         date  number symbol
0  2017-12-14       1      A
1  2017-12-15       2      B
2  2017-12-16       3      C

>>> df2.index
RangeIndex(start=0, stop=3, step=1)

>>> df2.columns
Index([u'date', u'number', u'symbol'], dtype='object')

今回の例で言えば、dfdf2の内容は同じですかね。

Reference(official documents)

32
19
1

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
32
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?