7. Random Numbers#

  • Generate random data/numbers of any shape

    • rand generates any random data

    • randn generates data such that mean is 0 and Standard distribution is 1

    • randint generates integer data between your specified range

import numpy as np
import pandas as pd
np.random.randn(3) # 3 elements
array([-0.20572628, -1.00766546, -0.39290176])
np.random.randn(3,4) # 3 rows x 4 cols
array([[ 1.4588499 , -0.14540371,  0.28350866,  0.59364454],
       [ 0.46931889,  0.8139862 ,  0.83492824,  0.92948039],
       [ 0.45270461,  1.28071728, -0.2820784 ,  1.34523256]])

7.1. Examples#

np.random.randint(1,5,(3,4)) # Give me data from 1 to 5 of 3 rows and 4 cols
array([[3, 4, 3, 2],
       [2, 2, 1, 1],
       [4, 1, 3, 2]])

8. Convert arrays to dataframe#

pd.DataFrame(np.random.randn(3,4)) # 3x4=12 elements
0 1 2 3
0 0.759206 2.327923 -0.521909 0.789482
1 -0.563490 0.624165 0.998313 0.389569
2 1.918592 -0.907093 -2.182463 -0.714627

8.1. Reshaping the data#

a=np.random.randint(1,5,(3,4)) # 4x3=12 elements
a.reshape(6,2) # 6x2=12 so it will generate data
array([[2, 3],
       [3, 4],
       [1, 4],
       [2, 2],
       [4, 4],
       [4, 1]])
a.reshape(6,3) # it will through data because 6x3=18 elements and we don't have 18 elements
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Input In [8], in <cell line: 1>()
----> 1 a.reshape(6,3)

ValueError: cannot reshape array of size 12 into shape (6,3)