numpy Selecting a random sample from an array


Example

letters = list('abcde')

Select three letters randomly (with replacement - same item can be chosen multiple times):

np.random.choice(letters, 3)
''' 
Out: array(['e', 'e', 'd'], 
      dtype='<U1')
'''

Sampling without replacement:

np.random.choice(letters, 3, replace=False)
''' 
Out: array(['a', 'c', 'd'], 
      dtype='<U1')
'''

Assign probability to each letter:

# Choses 'a' with 40% chance, 'b' with 30% and the remaining ones with 10% each
np.random.choice(letters, size=10, p=[0.4, 0.3, 0.1, 0.1, 0.1])

'''
Out: array(['a', 'b', 'e', 'b', 'a', 'b', 'b', 'c', 'a', 'b'],
  dtype='<U1')
'''