pandasの行・列をランダムサンプリング(抽出)するsample
行数の多いpandas.DataFrame
, pandas.Series
のデータを確認するときに、行または列をランダムに抽出(ランダムサンプリング)するメソッドsample()
が便利。
なお、大きいサイズのpandas.DataFrame
, pandas.Series
のデータを確認するときに使えるほかのメソッドとして、先頭・末尾の行を返すhead()
とtail()
もある。
ここでは以下の内容について説明する。
sample()
のデフォルト動作- 抽出する行数・列数を指定: 引数
n
- 抽出する行・列の割合を指定: 引数
frac
- 乱数シードを固定: 引数
random_state
- 重複を許可: 引数
replace
- 行・列を指定: 引数
axis
例として、seabornにサンプルとして含まれているirisデータセットを使う。pandas.DataFrame
なのでそのまま使えて便利。
import pandas as pd
import seaborn as sns
df = sns.load_dataset("iris")
print(df.shape)
# (150, 5)
source: pandas_sample.py
例はpandas.DataFrame
だが、pandas.Series
でもsample()
が用意されている。引数など、使い方は同じ。
スポンサーリンク
sample()のデフォルト動作
引数を何も指定しないと、ランダムで1行が返される。
print(df.sample())
# sepal_length sepal_width petal_length petal_width species
# 108 6.7 2.5 5.8 1.8 virginica
source: pandas_sample.py
抽出する行数・列数を指定: 引数n
引数n
で抽出する行数・列数を指定できる。
print(df.sample(n=3))
# sepal_length sepal_width petal_length petal_width species
# 3 4.6 3.1 1.5 0.2 setosa
# 1 4.9 3.0 1.4 0.2 setosa
# 96 5.7 2.9 4.2 1.3 versicolor
source: pandas_sample.py
抽出する行・列の割合を指定: 引数frac
引数frac
で抽出する行・列の割合を指定できる。1
だと100%。n
とfrac
を同時に指定することは出来ない。
print(df.sample(frac=0.04))
# sepal_length sepal_width petal_length petal_width species
# 119 6.0 2.2 5.0 1.5 virginica
# 97 6.2 2.9 4.3 1.3 versicolor
# 46 5.1 3.8 1.6 0.2 setosa
# 137 6.4 3.1 5.5 1.8 virginica
# 56 6.3 3.3 4.7 1.6 versicolor
# 62 6.0 2.2 4.0 1.0 versicolor
source: pandas_sample.py
乱数シードを固定: 引数random_state
引数random_state
で乱数シードを指定することができる。乱数シードが固定されて、常に同じ行・列が返されるようになる。
print(df.sample(n=3, random_state=0))
# sepal_length sepal_width petal_length petal_width species
# 114 5.8 2.8 5.1 2.4 virginica
# 62 6.0 2.2 4.0 1.0 versicolor
# 33 5.5 4.2 1.4 0.2 setosa
source: pandas_sample.py
重複を許可: 引数replace
引数replace
をTrue
とすると、抽出される行・列の重複が許可される。デフォルトはFalse
。
replace=True
の場合、元の行数・列数以上のサンプリング数を指定できる。
print(df.head(3).sample(n=3, replace=True))
# sepal_length sepal_width petal_length petal_width species
# 2 4.7 3.2 1.3 0.2 setosa
# 1 4.9 3.0 1.4 0.2 setosa
# 1 4.9 3.0 1.4 0.2 setosa
print(df.head(3).sample(n=5, replace=True))
# sepal_length sepal_width petal_length petal_width species
# 1 4.9 3.0 1.4 0.2 setosa
# 0 5.1 3.5 1.4 0.2 setosa
# 1 4.9 3.0 1.4 0.2 setosa
# 0 5.1 3.5 1.4 0.2 setosa
# 0 5.1 3.5 1.4 0.2 setosa
source: pandas_sample.py
行・列を指定: 引数axis
引数axis
を1
とすると列をランダムに抽出できる。ここまでの例のように、デフォルトは0
(行)。
print(df.head().sample(n=2, axis=1))
# sepal_width species
# 0 3.5 setosa
# 1 3.0 setosa
# 2 3.2 setosa
# 3 3.1 setosa
# 4 3.6 setosa
source: pandas_sample.py
スポンサーリンク