9
16

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.

疑似乱数生成とランダムサンプリング

Last updated at Posted at 2014-09-10

標準モジュールで乱数を生成する

Python には標準ライブラリとして random モジュールが備わっており、さまざまな分布の乱数を生成することができます。これには主に次のような特長があります。

  • よく使うメジャーな分布である一様分布、正規分布、対数正規分布、負の指数分布、ガンマおよびベータ分布を利用できる。
  • 乱数生成器として C で実装されたメルセンヌツイスタ (MT) を利用している。
  • Random をサブクラス化して乱数生成器を自作することもできる。

乱数生成例

NumPy のランダムサンプル関数では浮動小数点数または整数などでの乱数生成ができます。

np.random.random_sample((5,))
#=> array([ 0.80055457,  0.19615444,  0.50532311,  0.48243283,  0.56227889])

np.random.random_sample((5,2))
#=>
# array([[ 0.59495428,  0.56194628],
#        [ 0.93675326,  0.88873404],
#        [ 0.98967746,  0.2319963 ],
#        [ 0.20625308,  0.76956028],
#        [ 0.7870824 ,  0.30181687]])

データフレームのランダムな並び替え

permutation を利用することでデータフレームのランダムな並び替えができます。

df = pd.DataFrame(np.arange(10*4).reshape(10,4))
sampler = np.random.permutation(5)
#=> array([0, 2, 1, 3, 4])

df.take(sampler)
#=>
#     0   1   2   3
# 0   0   1   2   3
# 2   8   9  10  11
# 1   4   5   6   7
# 3  12  13  14  15
#4  16  17  18  19

np.random.permutation(len(df))
#=> array([6, 7, 8, 3, 9, 4, 2, 1, 0, 5])

トランプを引く

52 枚のトランプの山から 10 枚引くコードを考えてみます。 random.shuffle を使えばシャッフルできますから、ここから任意の枚数を引けば良いでしょう。

# トランプの山を用意する
deck = list(
    itertools.product(list(range(1, 14)),
                      ['スペード', 'ハート', 'ダイヤ', 'クラブ']))

random.shuffle(deck) # デッキをシャッフルする

print("引いたカード:")
for i in range(10): # 10 枚のカードを引く
    print(deck[i][1] + "の " + str(deck[i][0]))

#=> 引いたカード:
# ダイヤの 6
# クラブの 3
# ハートの 10
# ダイヤの 12
# スペードの 8
# クラブの 13
# ダイヤの 13
# スペードの 5
# ハートの 12
# ダイヤの 7

トランプは 52 枚しか無いので random.shuffle(53) とすると IndexError になります。

9
16
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
9
16

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?