Breaking News

# Numpy Random Array

5 – Random Array

### NumPy Random Array¶

In [2]:
import numpy as np

In [3]:
# generate a random scalar
print(np.random.rand())

0.2224104911171324

In [4]:
# generate a 1-D array
print(np.random.rand(3))

[0.69589689 0.9990713  0.77034202]

In [5]:
# generate a 2-D array
print(np.random.rand(3,3))

[[0.2151302  0.64925559 0.95982155]
[0.02673682 0.33937101 0.78181161]
[0.39285799 0.7581885  0.15635241]]


### Generate a sample from the standard normal distribution (mean = 0, var = 1)¶

In [6]:
print(np.random.randn(3,3))

[[-0.6237973   0.61641124  0.3906358 ]
[ 1.17826888 -0.98635482 -2.53764331]
[ 1.27182989 -0.89890487  0.45915569]]


### 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'))

[4 2 3]


### 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))

[0.49861164 0.70069766 0.31124961 0.54764381 0.54914003 0.38105886
0.34266046 0.20683399 0.81448764 0.41120203]
[0.51783261 0.52871952 0.07454513 0.99254774 0.56647422 0.44681572
0.72867612 0.87028678 0.56413488 0.87260274]
[0.46954496 0.39286135 0.77653959 0.71686349 0.30688967 0.57456171
0.79837421 0.46358688 0.94360218 0.82150656]
[0.94433888 0.03255612 0.06258668 0.30156153 0.53547477 0.37340683
0.05315354 0.97134013 0.51253718 0.59354506]


### 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]))

[1 1 2 1 1 1 1 2 1 1]

In [10]:
print(np.random.choice(3, 10))

[1 1 1 0 1 0 2 0 0 2]

In [11]:
print(np.random.choice([1,2,3], 10))

[3 2 3 3 3 3 3 2 1 2]


### Shuffle an array in place¶

In [12]:
arr = np.array(range(10))
print(arr)

[0 1 2 3 4 5 6 7 8 9]

In [13]:
np.random.shuffle(arr)
print(arr)

[1 5 0 6 4 9 2 3 7 8]


### 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))

The initial array:  [0 1 2 3 4 5 6 7 8 9]
A permutation of the array:  [1 8 7 9 3 6 0 4 5 2]