numpy sample code example

Example 1: python select random subset from numpy array

fruits = ['apple', 'banana', 'orange', 'grape']
subset_size = int(0.7 * len(fruits))
np.random.choice(fruits, subset_size, replace=False)
# array(['grape', 'banana'], dtype='<U6')

Example 2: how to import numpy array in python

>>> import numpy as np
>>> a = np.array([0, 1, 2, 3])
>>> a
array([0, 1, 2, 3])

Example 3: numpy random choice

>>> np.random.choice(5, 3, p=[0.1, 0, 0.3, 0.6, 0])
array([3, 3, 0])

Example 4: numpy random for string

>>> aa_milne_arr = ['pooh', 'rabbit', 'piglet', 'Christopher']
>>> np.random.choice(aa_milne_arr, 5, p=[0.5, 0.1, 0.1, 0.3])
array(['pooh', 'pooh', 'pooh', 'Christopher', 'piglet'],
      dtype='|S11')



fruits = ['apple', 'banana', 'orange', 'grape']
subset_size = int(0.7 * len(fruits))
np.random.choice(fruits, subset_size, replace=False)
# array(['grape', 'banana'], dtype='<U6')