2015年12月22日

pandasでDataFrameの最初の行のSeriesを取る

こんなDataFrameがあったとする。

import numpy as np
import pandas as pd

arr = np.random.random(15).reshape(5, 3)
df = pd.DataFrame( columns, name=['a', 'b', 'c'] )

  #=>           a         b         c
  #=> 0  0.917560  0.521009  0.172845
  #=> 1  0.597055  0.710881  0.325102
  #=> 2  0.679755  0.371444  0.106615
  #=> 3  0.109112  0.573387  0.571458
  #=> 4  0.578527  0.262368  0.723052

これの1行目をSeriesで取得する場合、このままであればlocで取れる。

df.loc[0]

  #=> a    0.917560
  #=> b    0.521009
  #=> c    0.172845
  #=> Name: 0, dtype: float64

しかしこれはindexの0を取っているので1行目を取っているわけではなく、set_indexするなり条件で間引いてindexに0がいることが保証されなくなると、動かなくなる。

df.set_index('a').loc[0]
  #=> KeyError: 'the label [0] is not in the [index]'

この場合はilocで取れる。

df.set_index('a').iloc[0]

  #=> b    0.521009
  #=> c    0.172845
  #=> Name: 0.917559773465, dtype: float64

ずっとilocなるものがあることに気づかず、valuesで取るとかreset_indexしてlocで取るとか変なことをしていた。