IKH

Creation of Arrays – II

Diag()

  • diag(v, k=0) ==> Extract a diagonal or construct a diagonal array.
  • If we provide 2-D array then it will extract the elements at k-th diagonal.
  • If we provide 1-D array the it will construct a diagonal array with the provided elements and remaining elements are filled with zeros.

Example

Python
import numpy as np
help(np.diag)

Output

PowerShell
Help on function diag in module numpy:

diag(v, k=0)
    Extract a diagonal or construct a diagonal array.

Example

Python
# Extract 2-D diagonal elements
a = np.arange(1,10).reshape(3,3)
print(f"Original 2-D array ==> \n {a}")
print(f"Elements prsent at 0-diagonal ==> {np.diag(a,k=0)}")
print(f"Elements prsent at 1-diagonal ==> {np.diag(a,k=1)}")
print(f"Elements prsent at 2-diagonal ==> {np.diag(a,k=2)}")
print(f"Elements prsent at -1-diagonal ==> {np.diag(a,k=-1)}")
print(f"Elements prsent at -2-diagonal ==> {np.diag(a,k=-2)}")
print(f"Elements prsent at 3-diagonal ==> {np.diag(a,k=3)}")

Output

PowerShell
Original 2-D array ==>
[[1 2 3]
[4 5 6]
[7 8 9]]
Elements prsent at 0-diagonal ==> [1 5 9]
Elements prsent at 1-diagonal ==> [2 6]
Elements prsent at 2-diagonal ==> [3]
Elements prsent at -1-diagonal ==> [4 8]
Elements prsent at 2-diagonal ==> [7]
Elements prsent at -1-diagonal ==> []

Example

Python
# 1-D construct 2-D array with the diagonal array with the provided elements
# remaining elements are filled with zeros
a = np.array([10,20,30,40])
np.diag(a,k=0)

Output

PowerShell
array([[10,  0,  0,  0],
       [ 0, 20,  0,  0],
       [ 0,  0, 30,  0],
       [ 0,  0,  0, 40]]),

Example

Python
np.diag(a,k=1)

Output

PowerShell
array([[[ 0, 10,  0,  0,  0]
        [ 0,  0, 20,  0,  0]
        [ 0,  0,  0, 30,  0]
        [ 0,  0,  0,  0, 40]
        [ 0,  0,  0,  0,  0]])

Example

Python
np.diag(a,k=-1)

Output

PowerShell
array([[[ 0,  0,  0,  0,  0]
        [10,  0,  0,  0,  0]
        [ 0, 20,  0,  0,  0]
        [ 0,  0, 30,  0,  0]
        [ 0,  0,  0, 40,  0]])

empty()

  • Return a new array of given shape and type, without initializing entries.

Example

Python
import numpy as np
help(np.empty)

Output

PowerShell
Help on built-in function empty in module numpy:

empty(...)
    empty(shape, dtype=float, order='C', *, like=None)
Return a new array of given shape and type, without initializing entries.

Example

Python
np.empty((3,3))

Output

PowerShell
array([[0.00000000e+000, 0.00000000e+000, 0.00000000e+000],
       [0.00000000e+000, 0.00000000e+000, 6.42285340e-321],
       [4.47593775e-091, 4.47593775e-091, 1.06644825e+092]])

Note

  • There is no default value in C language.
  • So if value is initialized then it will be assigned with some garbage values.
  • Generally ’empty()’ function is ued to create dummy array-.
  • np.empty(10) returns uninitialized data ==> we can use this for future purpose.

zeros() vs empty()

  • If we required an array only with zeros then we should go for zeros().
  • If we never worry about data, just we required an empty array for future purpose, then we should go for empty().
  • The time required to create emtpy array is very very less when compared with zeros array. i.e performance wise empty() function is recommended than zeros() ifwe are not worry about data.

Example

Python
# performance comaparision of zeros() and empty()
import numpy as np
from datetime import datetime
import sys

begin = datetime.now()
a = np.zeros((10000,300,400))
after = datetime.now()
print('Time taken by zeros:',after-begin)

a= None
begin = datetime.now()
a = np.empty((10000,300,400))
after = datetime.now()
print('Time taken by empty:',after-begin)

Output

PowerShell
Time taken by zeros: 0:00:00.027922
Time taken by empty: 0:00:00.028924

Note

  • Numpy : basic datatype ==> ndarray.
  • Scipy : Advance Numpy.
  • Pandas : basic datatypes => Series(1-D) and DataFrame(Multi dimensional) basedon Numpy.
  • Matplotlib : Data visualization module.
  • Seaborn, plotly : based on Matplotlib.

np.random module

  • This library contains several functions to create nd arrays with random data.

randint

  • To generate random int values in the given range.

Example

Python
import numpy as np
help(np.random.randint)

Output

PowerShell
Help on built-in function randint:

randint(...) method of numpy.random.mtrand.RandomState instance
    randint(low, high=None, size=None, dtype=int)
    
    Return random integers from `low` (inclusive) to `high` (exclusive).
    
    Return random integers from the "discrete uniform" distribution of
    the specified dtype in the "half-open" interval [`low`, `high`). If
   `high` is None (the default), then results are from [0, `low`).
randint(low, high=None, size=None, dtype=int)
  • Return random integers from low (inclusive) to high (exclusive).
  • it is represented as [ low , high ) ==> [ means inclusive and ) means exclusive.
  • If high is None (the default), then results are from [0, low ).

Example

Python
# it will generate a single random int value in the range 10 to 19.
np.random.randint(10,20)

Output

PowerShell
10

Example

Python
# To create 1-D ndarray of size 10 with random values from 1 to 8?
np.random.randint(1,9,size=10)

Output

PowerShell
array([8, 4, 8, 7, 4, 3, 8, 6, 5, 8])

Example

Python
# To create 2D array with shape(3,5)
np.random.randint(100,size=(3,5))

Output

PowerShell
array([[98, 32, 45, 60, 7],
       [97, 42, 71, 0, 17],
       [17, 44, 2, 29, 45]])

Example

Python
# from 0 to 99 random values, 2-D array will be created. Here high is None
np.random.randint(100,size=(3,5))

Output

PowerShell
array([[92, 29, 24, 20, 56],
       [12, 20, 54, 83, 12],
       [ 5, 17, 55, 60, 62]])

Example

Python
# To create 3D array with shape(2,3,4)
# 3D array contains 2 2-D arrays
# Each 2-D array contains 3 rows and 4 columns
# np.random.randint(100,size=(2,3,4))
np.random.randint(100,size=(2,3,4))

Output

PowerShell
array([[[35,  1, 54, 25],
        [ 5, 44, 93, 60],
        [27, 24, 23, 51]],
        
        [[65, 55, 22, 74],
         [76, 19,  9, 43],
         [17, 44, 58, 52]]])

Example

Python
# randint(low, high=None, size=None, dtype=int)
# dtype must be int types
# int types
# int8
# int16
# int32 (default)
# int64
a = np.random.randint(1,11,size=(20,30))
print(f"Data type of the elements : {a.dtype}")

Output

PowerShell
Data type of the elements : int32

Example

Python
# memory utilization is improved with dtype
import sys
a = np.random.randint(1,11,size=(20,30))
print(f"with int32 size of ndarray : {sys.getsizeof(a)}")
a = np.random.randint(1,11,size=(20,30),dtype='int8')
print(f"with int8 size of ndarray : {sys.getsizeof(a)}")

Output

PowerShell
with int32 size of ndarray : 2520
with int8 size of ndarray : 720

astype() ==> To convert the data type from one form to another

Example

Python
# we can convert the datatype to another.
# by default randint() will return int datatype.
# by using "astype()" we can convert one datatype to another
a = np.random.randint(1,11,size=(20,30))
print("Before Conversion ")
print(f"Data type of a ==> {a.dtype}")
b = a.astype('float')
print("Ater calling astype() on the ndarray a ")
print(f"Data type of b==> {b.dtype}")

Output

PowerShell
Before Conversion
Data type of a ==> int32
Ater calling astype() on the ndarray a
Data type of b==> float64

Uniform distribution Vs Normal Distribution

  • Normal distribution is a probability distribution where probability of x is highest at centre and lowest in the ends whereas in uniform distribution probability of x is constant.
  • Uniform distribution is a probability distribution where probability of x is constant.

FIGAR BANANA H

rand()

  • It will generates random float values in the range [0,1) from uniform distribution samples.
  • [0 ==> means 0 is incluede and 1) ==> means 1 is excluded.

Example

Python
import numpy as np
help(np.random.rand)

Output

PowerShell
Help on built-in function rand:

rand(...) method of numpy.random.mtrand.RandomState instance
rand(d0, d1, ..., dn)

Random values in a given shape.
rand(d0, d1, …, dn)
  • Random values in a given shape.

Example

Python
# single random float value from 0 to 1
np.random.rand()

Output

PowerShell
0.08638507965381459

Example

Python
# 1-D array with float values from 0 to 1
np.random.rand(10)

Output

PowerShell
array([0.39130964, 0.4701559 , 0.49176215, 0.38386718, 0.35090334,
       0.02928118, 0.96359654, 0.41079371, 0.38436428, 0.81939376])

Example

Python
# 2-D array with float values from 0 to 1
np.random.rand(3,5)

Output

PowerShell
array([[0.64607105, 0.92823898, 0.48098258, 0.52641539, 0.09602147],
       [0.36884988, 0.29296605, 0.87343336, 0.67168146, 0.09297364],
       [0.21607014, 0.14382148, 0.47534017, 0.84083409, 0.73185496]])

Example

Python
# 3-D array with float values from 0 to 1
np.random.rand(2,3,4)

Output

PowerShell
array([[[0.83901492, 0.03543901, 0.76098031, 0.46620334],
        [0.25545172, 0.24279657, 0.66570238, 0.34390092],
        [0.44146884, 0.04426514, 0.59433418, 0.25362922]],
        
       [[0.88437233, 0.04283568, 0.57814391, 0.91268089],
        [0.72943145, 0.95593275, 0.26450772, 0.75816229],
        [0.74559404, 0.22803979, 0.34306227, 0.33591768]]])

uniform()

  • rand() ==> range is always [0,1)
  • uniform() ==> customize range [low,high)

Example

Python
import numpy as np
help(np.random.uniform)

Output

PowerShell
Help on built-in function uniform:

uniform(...) method of numpy.random.mtrand.RandomState instance
    uniform(low=0.0, high=1.0, size=None)
    
Draw samples from a uniform distribution.

Samples are uniformly distributed over the half-open interval
``[low, high)`` (includes low, but excludes high). In other words,
any value within the given interval is equally likely to be drawn
by `uniform`.

Example

Python
# uniform(low=0.0, high=1.0, size=None)
np.random.uniform() # it will acts same as np.random.rand()

Output

PowerShell
0.8633674116602018

Example

Python
# random float value in the given customized range
np.random.uniform(10,20)

Output

PowerShell
10.297706247279303

Example

Python
# 1-D array with customized range of float values
np.random.uniform(10,20,size=10)

Output

PowerShell
array([16.25675741, 10.57357925, 18.09157687, 19.07874982, 17.06463829,
       11.98365064, 12.01449467, 10.8823314 , 18.03513355, 17.66067279])

Example

Python
# 2-D array with customized range of float values
np.random.uniform(10,20,size=(3,5))

Output

PowerShell
array([[16.96942587, 15.68977979, 16.09812119, 13.06668784, 15.36258784],
       [14.55135047, 10.27434721, 19.46874406, 16.33163335, 19.07160274],
       [15.1368871 , 18.83658294, 10.66735409, 14.30008464, 13.79529403]])

Example

Python
# 3-D array with customized range of float values
np.random.uniform(10,20,size=(2,3,4))

Output

PowerShell
array([[[19.71747034, 13.13603927, 13.55533583, 13.49569866],
        [18.18364556, 11.64037815, 13.12254598, 10.73172933],
        [18.44982662, 11.48966867, 15.66803442, 12.37854234]],
        
       [[16.01656014, 12.22451809, 18.524565 , 17.29353028],
        [15.33632839, 17.41720778, 17.3426583 , 12.98066622],
        [17.02012869, 19.74650958, 15.33698393, 16.86296185]]])

Example

Python
# to demonstrate the Unifrom distribution in data visualization
s = np.random.uniform(20,30,size=1000000)
import matplotlib.pyplot as plt
count, bins, ignored = plt.hist(s, 15, density=True)
plt.plot(bins, np.ones_like(bins), linewidth=2, color='r')
plt.show()

Output

PowerShell
output nhi diya h

FIGAR BANANA H

randn()

  • values from normal distribution with mean 0 and varience(stadard deviation) is 1.

Example

Python
import numpy as np
help(np.random.randn)

Output

PowerShell
Help on built-in function randn:

randn(...) method of numpy.random.mtrand.RandomState instance
randn(d0, d1, ..., dn)

Return a sample (or samples) from the "standard normal" distribution.

Example

Python
# randn(d0, d1, ..., dn)
# single float value including -ve value also
a = np.random.randn()
print(a)

Output

PowerShell
-0.0563667809620408

Example

Python
# 1-D array with mean 0 and stand deviation 1
a = np.random.randn(10)
print(a)
print(f"Mean ==> {a.mean()}")
print(f"Variance ==> {a.var()}")
print(f"Standard deviation ==> {a.std()}")

Output

PowerShell
[-2.59949374 1.07020758 -1.525435      0.97692928 0.71398471 -0.08671092
  0.07833857 0.70247123 0.94548715     0.38984236]
Mean ==> 0.06656212089297449
Variance ==> 1.3202568278489202
Standard deviation ==> 1.1490242938462703

Example

Python
# 2-D array with float values in normal distribution
np.random.randn(2,3)

Output

PowerShell
array([[-1.84491706e+00, -1.80823278e-03, 1.61444938e-01],
       [-1.05642111e-01, 1.38334944e+00, -8.11945928e-01]])

Example

Python
# 3-D array with float values in normal distribution
np.random.randn(2,3,4)

Output

PowerShell
array([[[-0.67500418, -0.04050421, -1.28250359, -0.22205388],
        [-0.82973108, 0.69627796, -0.44151688, -1.05482818],
        [-0.39583573, -0.45231744, 0.72255689, -2.02508302]],
        
       [[ 0.56678912, -0.07604355, -0.62011088, -1.57825963],
        [-0.51442293, 0.52223471, 0.44212152, 0.85563198],
        [-1.17712106, 0.06659177, -2.06951363, -0.39449518]]])
  • randint() ==> To generate random int values in the given range.
  • rand() ==> uniform distribution in the range [0,1).
  • uniform() ==> uniform distribution in our provided range.
  • randn() ==> normal distribution values with mean 0 and variance is 1.
  • normal() ==> normal distribution values with our mean and variance.

normal()

  • We can customize mean and variance.

Example

Python
import numpy as np
help(np.random.normal)

Output

PowerShell
Help on built-in function normal:

normal(...) method of numpy.random.mtrand.RandomState instance
    normal(loc=0.0, scale=1.0, size=None)
    
Draw random samples from a normal (Gaussian) distribution.

normal(loc=0.0, scale=1.0, size=None)

  • loc : float or array_like of floats.
  • Mean (“centre”) of the distribution.
  • scale : float or array_like of floats.
  • Standard deviation (spread or “width”) of the distribution. Must be non-negative.
  • size : int or tuple of ints, optional.

Example

Python
# equivalent ot np.random.randn()
np.random.normal()

Output

PowerShell
-1.5337940293701702

Example

Python
# 1-D array with float values in normal distribution
a = np.random.normal(10,4,size=10)
print(f" a ==> {a}")
print(f"Mean ==> {a.mean()}")
print(f"Variance ==> {a.var()}")
print(f"Standard deviation ==> {a.std()}")

Output

PowerShell
a ==>  [12.58568061 12.65559388  2.05077827 11.47857117  8.28240666

        5.81919127 13.26960627  7.08689804 14.17971283 12.81610858]
Mean ==> 10.022454758081924
Variance ==> 14.411542333115623
Standard deviation ==> 3.7962537234905183

Example

Python
# 2-D array with float values in normal distribution
np.random.normal(10,4,size=(3,5))

Output

PowerShell
array([[ 9.60636406, 10.55287084, 13.58021522, 8.25985296, 12.12854933],
       [ 8.93107829, 3.37094761, 8.64304598, 11.32689884, 20.16374935],
       [ 7.09621692, 10.86554327, 5.52023479, 9.4032508 , 9.75254932]])

Example

Python
# 3-D array with float values in normal distribution
np.random.normal(10,4,size=(2,3,4))

Output

PowerShell
array([[[13.00647353, 11.55193581,  7.71907516, 8.66954042],
        [ 6.94062911, 9.64218428,   9.57700968, 11.82765693],
        [16.17363874, 6.88623436,   8.78229986, 5.41236423]],
        
       [[13.34349311, 14.04491431, 0.86900938, 9.72759205],
        [ 8.67789112, 7.02952354, 9.19535948, 15.08727821],
        [ 3.05669971, 12.80722846, 15.10007439, 14.21390539]]])

Example

Python
# to demonstrate the Unifrom distribution in data visualization
s = np.random.normal(10,4,1000000)
import matplotlib.pyplot as plt
count, bins, ignored = plt.hist(s, 15, density=True)
plt.plot(bins, np.ones_like(bins), linewidth=2, color='r')
plt.show()

FIGAR BNANA

shuffle()

  • Modify a sequence in-place by shuffling its contents.
  • This function only shuffles the array along the first axis of a multi-dimensionalarray.(axis-0).
  • The order of sub-arrays is changed but their contents remains the same.

Example

Python
import numpy as np
help(np.random.shuffle)

Output

PowerShell
Help on built-in function shuffle:

shuffle(...) method of numpy.random.mtrand.RandomState instance
    shuffle(x)
    Modify a sequence in-place by shuffling its contents.
    
    This function only shuffles the array along the first axis of a
    multi-dimensional array. The order of sub-arrays is changed but
    their contents remains the same.

Example

Python
# 1-D array
a = np.arange(9)
print(f'a before shuffling : {a}')
np.random.shuffle(a) # inline shuffling happens
print(f'a after shuffling : {a}')

Output

PowerShell
a before shuffling : [0 1 2 3 4 5 6 7 8]
a after shuffling :  [0 6 1 8 4 2 5 3 7]

Example

Python
# 2-D array
# (6,5)
# axis-0 : number of rows(6)
# axis-1 : number of columns(5)
# This function only shuffles the array along the first axis of a multi-dimensional
array(axis-0).
# The order of sub-arrays is changed but their contents remains the same.
a = np.random.randint(1,101,size=(6,5))
print(f'a before shuffling ==> \n {a}')
np.random.shuffle(a) # inline shuffling happens
print(f'a after shuffling ==>\n {a}')

Output

PowerShell
a before shuffling ==>
[[ 26  4 63 66 37]
[ 65 85 14 51 68]
[ 59  3 22 25 50]
[ 4  42 40 81 79]
[ 50 83 70 13  2]
[100 54 95 39 67]]

a after shuffling ==>
[[ 59  3 22 25 50]
 [ 65 85 14 51 68]
 [100 54 95 39 67]
 [ 4 42 40 81 79]
 [ 26 4 63 66 37]
 [ 50 83 70 13 2]]

3-D array : (4,3,4)

  • 4 : number of 2-D arrays (axis-0) ==> Vertical.
  • 3 : rows in every 2-D array(axis-1) ==> Horizontal.
  • 4 : columns in every 2-D array(axis-1).
  • If we apply shuffle for 3-D array, then the order of 2-D arrays will be changed but not
  • its internal content.

FIGAR BNANA

Example

Python
a = np.arange(48).reshape(4,3,4)
print(f'Before shuffling 3-D array \n :{a}')
np.random.shuffle(a)
print(f'After shuffling 3-D array \n :{a}')
PowerShell
Before shuffling 3-D array
:[[[ 0 1 2 3]
 [ 4 5 6 7]
 [ 8 9 10 11]]
 
[[12 13 14 15]
 [16 17 18 19]
 [20 21 22 23]]
 
[[24 25 26 27]
 [28 29 30 31]
 [32 33 34 35]]
 
[[36 37 38 39]
 [40 41 42 43]
 [44 45 46 47]]]
 After shuffling 3-D array
:[[[36 37 38 39]
 [40 41 42 43]
 [44 45 46 47]]
 
[[12 13 14 15]
 [16 17 18 19]
 [20 21 22 23]]
 
[[24 25 26 27]
 [28 29 30 31]
 [32 33 34 35]]
 
 [[ 0  1  2  3]
  [ 4  5  6  7]
  [ 8  9 10 11]]]
  

Summary of random library functions:

  • randint() ==> To generate random int values in the given range.
  • rand() ==> To generate uniform distributed float values in [0,1).
  • uniform() ==> To generate uniform distributed float values in the given range.[low,high).
  • randn() ==> normal distributed float values with mean 0 and standard deviation 1.
  • normal() ==> normal distributed float values with specified mean and standard deviation.
  • shuffle() ==> To shuffle order of elements in the given nd array.

Ungraded Questions

Get ready for an exhilarating evaluation of your understanding! Brace yourself as we dive into the upcoming assessment. Your active participation is key, so make sure to attend and demonstrate your knowledge. Let’s embark on this exciting learning journey together!


Name
Email
Phone

Report an error