NumPy Random Array¶
In [2]:
import numpy as np
In [3]:
# generate a random scalar
print(np.random.rand())
In [4]:
# generate a 1-D array
print(np.random.rand(3))
In [5]:
# generate a 2-D array
print(np.random.rand(3,3))
Generate a sample from the standard normal distribution (mean = 0, var = 1)¶
In [6]:
print(np.random.randn(3,3))
Generate an array of random integers in a given interval [low, high)¶
In [7]:
# np.ranodm.randint(low, high, size, dtype)
print(np.random.randint(1, 10, 3, 'i8'))
Generate an array of random floating-point numbers in the interval [0.0, 1.0)¶
In [8]:
# the following methods are the same as np.random.rand()
print(np.random.random_sample(10))
print(np.random.random(10))
print(np.random.ranf(10))
print(np.random.sample(10))
Generate a random sample from a given 1-D array¶
In [9]:
# np.random.choice(iterable_or_int, size, replace=True, p=weights)
print(np.random.choice(range(3), 10, replace=True, p=[0.1, 0.8, 0.1]))
In [10]:
print(np.random.choice(3, 10))
In [11]:
print(np.random.choice([1,2,3], 10))
Shuffle an array in place¶
In [12]:
arr = np.array(range(10))
print(arr)
In [13]:
np.random.shuffle(arr)
print(arr)
Generate a permutation of an array¶
In [14]:
# similar to np.random.shuffle(), but it returns a copy rather than making changes in place
arr = np.array(range(10))
print('The initial array: ', arr)
print('A permutation of the array: ', np.random.permutation(arr))