2015年08月05日

pandasでDataFrameにrandomな値を持つ列を追加するサンプルコード

ランダム値を持つ列を追加したかった。

とりあえずaxis=1でconcatすれば良いか、ということでこんな記述をしてみる

import numpy as np
import pandas as pd
df = pd.DataFrame( [ [1.1, 1.2, 1.3], [2.1, 2.2, 2.3], [3.1, 3.2, 3.3] ], columns=['a', 'b', 'c'] )
  #=>     a    b    c
  #=>0  1.1  1.2  1.3
  #=>1  2.1  2.2  2.3
  #=>2  3.1  3.2  3.3

# randomな列を持つDataFrameを作ってconcat
df = pd.concat( [ df, pd.DataFrame( np.random.random( len( df ) ), columns=['rand'] ) ], axis=1 )
  #=>     a    b    c      rand
  #=>0  1.1  1.2  1.3  0.721488
  #=>1  2.1  2.2  2.3  0.153180
  #=>2  3.1  3.2  3.3  0.865272

悪くはないけどキレイじゃない。他の方法を考える。

applyで良いか。

df['rand'] = df.a.apply( lambda x: np.random.random() )

コードとしてはシンプルだけどrandomを何度もコールするのは今ひとつ。

Seriesで代入した方が良さそう。

StackOverflowを見たら、こんな書き方が例示されていた。

df['rand'] = pd.Series( np.random.random( len(df) ), index=df.index )

うん、これが良さげ。