2015年02月13日

pandasでindexの連番を振り直す

sortして連番になっていたindexが乱れた時に振り直す想定。

# 適当なDataFrameを作る
df = pd.DataFrame( np.arange(0, 9).reshape(3, 3), columns=('a', 'b', 'c') )
  #=>    a  b  c
  #=> 0  0  1  2
  #=> 1  3  4  5
  #=> 2  6  7  8

# 適当にソートする
df.sort( 'b', inplace=True, ascending=False )
  #=>    a  b  c
  #=> 2  6  7  8
  #=> 1  3  4  5
  #=> 0  0  1  2

この時、indexが 2, 1, 0 になっているのを、0, 1, 2にしたい。

# df.reset_index( drop = True )
  #=>    a  b  c
  #=> 0  6  7  8
  #=> 1  3  4  5
  #=> 2  0  1  2

これで良いのだろうか。