You are on page 1of 71

1/13/24, 10:51 AM NUMPY

Numpy
Numpy is an python library We call it a python library because it supports python syntax.
It stands for numerical python.
Numpy is used to perform advance numerical computations on large data sets.
By using, Numpy we can perform complex operations with less line of code.
Numpy provides very useful Data-structure known as Array.

How to import Numpy ?


In [1]: import numpy as np

In [3]: arr = np.array([1,2,3,4,5])


print(arr , type(arr))

[1 2 3 4 5] <class 'numpy.ndarray'>

In [11]: lavish = np.array(["lavish","gangwani",23,2.0] , dtype = 'object')


print(lavish , type(lavish))

['lavish' 'gangwani' 23 2.0] <class 'numpy.ndarray'>

In [12]: lavish

array(['lavish', 'gangwani', 23, 2.0], dtype=object)


Out[12]:

Why we always use np.array function in every numpy dataset .?

np.array is a function in the numpy library that creates an array object. It is used to create
arrays of any dimension and data type. The numpy library is optimized for numerical
operations and provides a large number of functions for mathematical operations on arrays.

On the other hand, np.anything is not a valid function in the numpy library. If you meant to
ask whether you can use other functions in the numpy library instead of np.array, the answer
is yes. The choice of function depends on the specific task you are trying to accomplish. For
example, if you want to create an array of zeros, you can use the np.zeros function 1.

NumPy is a famous Python library used for working with arrays. One of the important
functions of this library is stack ().

NumPy is a library for the Python programming language, adding support for large, multi-
dimensional arrays and matrices, along with a large collection of high-level mathematical
functions…

NumPy is a famous Python library used for working with arrays. One of the important
functions of this library is stack ().

NumPy was created based on the Numeric code. The Numeric code was rewritten to be
easier to maintain, and new features could be added to the library.

localhost:8888/doc/tree/OneDrive/Desktop/PYTHON'S FILES/NUMPY.ipynb 1/80


1/13/24, 10:51 AM NUMPY

Most of the math functions have the same name in NumPy, so we can easily switch from
the non-vectorized functions from Python’s math module to NumPy’s versions.

What is the most important benefit of using NumPy?

A- Faster execution
B- Ease of use
C- Compatibility with other libraries
D- Availability of documentation

In [18]: a = np.array([1,2,3,"45"])
a

array(['1', '2', '3', '45'], dtype='<U11')


Out[18]:

In [19]: a = np.array([1,2,3,"45"] , dtype = 'object')


a

array([1, 2, 3, '45'], dtype=object)


Out[19]:

To Check the Version of your Numpy Library:

In [4]: np.__version__

'1.24.3'
Out[4]:

How to update Numpy?

conda update Numpy on anaconda prompt


Start> anaconda prompt

ARRAY :
It is an collection of Homogenous data.

Example : np.array([1,2,3,4,5])
As you can see all are in integer datatype.

In [23]: arr = np.array([1,2,3,4,5,6,7,8])


print(arr , type(arr))

[1 2 3 4 5 6 7 8] <class 'numpy.ndarray'>

LISTS VS ARRAY :
With array we can perform some operations which we can't perform with lists.
Array are way faster than list.
With list if we have to print a range or make changes in the range then we have to write
whole line of code.

localhost:8888/doc/tree/OneDrive/Desktop/PYTHON'S FILES/NUMPY.ipynb 2/80


1/13/24, 10:51 AM NUMPY

But with array we can simply do it.

In [27]: lst = [i for i in range(1,11)]


print(lst)

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

In [31]: print(lst*5)

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7,


8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

In [25]: # Multiply all the elements by 5.


lst = [i*5 for i in range(1,11)]
print(lst)

[5, 10, 15, 20, 25, 30, 35, 40, 45, 50]

In [28]: arr = np.array(lst)


arr

array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
Out[28]:

In [29]: arr*5

array([ 5, 10, 15, 20, 25, 30, 35, 40, 45, 50])
Out[29]:

As you can see the differences in upper codes like in list we cannot multiply *5 doesn't get
the multiplication elements but if you see with array we don't even have to mention print
function with it.

In [32]: arr*8

array([ 8, 16, 24, 32, 40, 48, 56, 64, 72, 80])
Out[32]:

In [33]: import time

In [37]: starTTime = time.time()

lst = [ i for i in range(1000000)]

endTime = time.time()

ActaulTime = endTime - starTTime

print(ActaulTime)

0.14682960510253906

In [36]: starTTime = time.time()

arr = np.array(100000)

endTime = time.time()

ActaulTime = endTime - starTTime

print(ActaulTime)

localhost:8888/doc/tree/OneDrive/Desktop/PYTHON'S FILES/NUMPY.ipynb 3/80


1/13/24, 10:51 AM NUMPY
0.0010006427764892578

Why Arrays are faster than list:


On list we can perform some operations.
List make proccess slow.
Array uses vectorisation method by using array broadcasting which make array way faster.
List contains Heterogenous data elements.
Array contains of homogenous Data elements.
As Lists have Heterogenous data elements it has to store each element seprately by which
it makes proccess slow.
As with Array have homogenous data elements so it cannot have to store elements
seprately.

Array upcasting :
We can store heterogenous elements in array by using array upcasting.
array upcasting converts all the heterogenous elements in 1 data type this is known as array
upcasting.

int < float < complex < string < object

In [38]: arr = np.array([1,2,3,4,5])


arr

array([1, 2, 3, 4, 5])
Out[38]:

In [39]: arr = np.array([1,2.0,3,4,5])


arr

array([1., 2., 3., 4., 5.])


Out[39]:

In [40]: arr = np.array([1,2,3+2j,4,5])


arr

array([1.+0.j, 2.+0.j, 3.+2.j, 4.+0.j, 5.+0.j])


Out[40]:

In [41]: arr = np.array([1,2,3,'4',5])


arr

array(['1', '2', '3', '4', '5'], dtype='<U11')


Out[41]:

In [42]: arr = np.array([1,2.0,3+4j,'4',5], dtype= 'object')


arr

array([1, 2.0, (3+4j), '4', 5], dtype=object)


Out[42]:

By using dtype = 'object' We can make array with heterogenous data elements as you can
see in above code.

In [44]: arr.dtype

localhost:8888/doc/tree/OneDrive/Desktop/PYTHON'S FILES/NUMPY.ipynb 4/80


1/13/24, 10:51 AM NUMPY
dtype('O')
Out[44]:

Create Different kinds of array :

np.arange()
It creates an array of numbers.

Syntax - np.arange(start , stop , step)

start - inclusive (0 By default)


stop - exclusive
step_size = 1 (By default)

In [45]: arr = np.arange(1,20,1)


arr

array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,


Out[45]:
18, 19])

In [46]: arr = np.arange(1,11)


arr

array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
Out[46]:

In [47]: arr = np.arange(11)


arr

array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
Out[47]:

In [9]: lst = [i for i in range(1,11)]


arr = np.arange(1,len(lst))
arr**3

array([ 1, 8, 27, 64, 125, 216, 343, 512, 729], dtype=int32)


Out[9]:

In [62]: lst = [i for i in range(1,11)]


arr = np.arange(1,len(lst),dtype = 'object')
arr**3

array([1, 8, 27, 64, 125, 216, 343, 512, 729], dtype=object)


Out[62]:

np.linspace()
It creates an array of equally spaced values within the range of values.

Syntax -

np.linspace(start , stop , Number of values you want within it)

By default, in linspace both the start and stop values are included
By default, linspace will return the answer in float

localhost:8888/doc/tree/OneDrive/Desktop/PYTHON'S FILES/NUMPY.ipynb 5/80


1/13/24, 10:51 AM NUMPY

In [63]: arr = np.linspace(2,5,4)


arr

array([2., 3., 4., 5.])


Out[63]:

As you can see start value is 2 and stop value is 5 by which in the range of 2,5 We need 4
values within it.

In [66]: arr = np.linspace(2,5,10)


arr

array([2. , 2.33333333, 2.66666667, 3. , 3.33333333,


Out[66]:
3.66666667, 4. , 4.33333333, 4.66666667, 5. ])

In [74]: arr = np.linspace(1,22,50)


arr

array([ 1. , 1.42857143, 1.85714286, 2.28571429, 2.71428571,


Out[74]:
3.14285714, 3.57142857, 4. , 4.42857143, 4.85714286,
5.28571429, 5.71428571, 6.14285714, 6.57142857, 7. ,
7.42857143, 7.85714286, 8.28571429, 8.71428571, 9.14285714,
9.57142857, 10. , 10.42857143, 10.85714286, 11.28571429,
11.71428571, 12.14285714, 12.57142857, 13. , 13.42857143,
13.85714286, 14.28571429, 14.71428571, 15.14285714, 15.57142857,
16. , 16.42857143, 16.85714286, 17.28571429, 17.71428571,
18.14285714, 18.57142857, 19. , 19.42857143, 19.85714286,
20.28571429, 20.71428571, 21.14285714, 21.57142857, 22. ])

np.zeros()
It will return an array of the given shape with all the elements of the array as zero.

Syntax

np.zeros((rows,columns))

By default it will return object in float datatype.

In [76]: np.zeros((3,3))

array([[0., 0., 0.],


Out[76]:
[0., 0., 0.],
[0., 0., 0.]])

In [77]: np.zeros((3,4))

array([[0., 0., 0., 0.],


Out[77]:
[0., 0., 0., 0.],
[0., 0., 0., 0.]])

In [80]: np.zeros((3,4,6), dtype = 'int')

localhost:8888/doc/tree/OneDrive/Desktop/PYTHON'S FILES/NUMPY.ipynb 6/80


1/13/24, 10:51 AM NUMPY
array([[[0, 0, 0, 0, 0, 0],
Out[80]:
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0]],

[[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0]],

[[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0]]])

np.ones()
It will return an array of the given shape with all the elements of the array as 1

Syntax

np.ones((rows , columns))

- By default it will return the object in float datatype.

In [81]: np.ones((3,3))

array([[1., 1., 1.],


Out[81]:
[1., 1., 1.],
[1., 1., 1.]])

In [82]: np.ones((3,4))

array([[1., 1., 1., 1.],


Out[82]:
[1., 1., 1., 1.],
[1., 1., 1., 1.]])

In [83]: np.ones((3,4,6), dtype ='int')

array([[[1, 1, 1, 1, 1, 1],
Out[83]:
[1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1]],

[[1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1]],

[[1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1]]])

np.full()

localhost:8888/doc/tree/OneDrive/Desktop/PYTHON'S FILES/NUMPY.ipynb 7/80


1/13/24, 10:51 AM NUMPY

It will return an array of the given shape with all the elements of the array as value you have
entered.

Syntax

np.full((rows , columns), values)

By default it will return the object in float datatype.

In [94]: np.full((3,3) , 22)

array([[22, 22, 22],


Out[94]:
[22, 22, 22],
[22, 22, 22]])

In [7]: np.full((3,4) ,"lavish", dtype = 'object')

array([['lavish', 'lavish', 'lavish', 'lavish'],


Out[7]:
['lavish', 'lavish', 'lavish', 'lavish'],
['lavish', 'lavish', 'lavish', 'lavish']], dtype=object)

AS you can see in above code np.full is used for creating an specific numbers array as you can
first we have to give rows and columns and then value we have to put it in.

In [6]: np.full((3,4) , 2.2)

array([[2.2, 2.2, 2.2, 2.2],


Out[6]:
[2.2, 2.2, 2.2, 2.2],
[2.2, 2.2, 2.2, 2.2]])

In [105… np.full((3,4) , 2+32j)

array([[2.+32.j, 2.+32.j, 2.+32.j, 2.+32.j],


Out[105]:
[2.+32.j, 2.+32.j, 2.+32.j, 2.+32.j],
[2.+32.j, 2.+32.j, 2.+32.j, 2.+32.j]])

In [108… np.full((3,4) , 2+32j , dtype = 'object')

array([[(2+32j), (2+32j), (2+32j), (2+32j)],


Out[108]:
[(2+32j), (2+32j), (2+32j), (2+32j)],
[(2+32j), (2+32j), (2+32j), (2+32j)]], dtype=object)

np.eye()
It will return an identity matrix
In an identity matrix, the diagonal elements are 1's and the non diagonal elements are 0's
By default, the values will be in float

Syntax :

np.eye(rows , columns)

In [85]: np.eye(4,4)

localhost:8888/doc/tree/OneDrive/Desktop/PYTHON'S FILES/NUMPY.ipynb 8/80


1/13/24, 10:51 AM NUMPY
array([[1., 0., 0., 0.],
Out[85]:
[0., 1., 0., 0.],
[0., 0., 1., 0.],
[0., 0., 0., 1.]])

In [93]: np.eye(3,4,6, dtype= 'int')

array([[0, 0, 0, 0],
Out[93]:
[0, 0, 0, 0],
[0, 0, 0, 0]])

As you can see in upper code I've given 3 values it is giving all in 0's not giving diagonals of
1's in it.

In [91]: np.eye(4,4, dtype= 'int')

array([[1, 0, 0, 0],
Out[91]:
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1]])

np.zeros_like()
It returns an array of 0's of the given shape of another array

In [3]: arr = np.array([[1,2,3,4],[2,3,4,5],[5,6,7,8]])


arr

array([[1, 2, 3, 4],
Out[3]:
[2, 3, 4, 5],
[5, 6, 7, 8]])

In [5]: np.zeros_like(arr)

array([[0, 0, 0, 0],
Out[5]:
[0, 0, 0, 0],
[0, 0, 0, 0]])

np.ones_like()
It returns an array of 1's of the given shape of another array

In [113… arr

array([[1, 2, 3, 4],
Out[113]:
[2, 3, 4, 5],
[5, 6, 7, 8]])

In [114… np.ones_like(arr)

array([[1, 1, 1, 1],
Out[114]:
[1, 1, 1, 1],
[1, 1, 1, 1]])

np.full_like()

localhost:8888/doc/tree/OneDrive/Desktop/PYTHON'S FILES/NUMPY.ipynb 9/80


1/13/24, 10:51 AM NUMPY

It will return an array of the given shape with all the elements of the array as value you have
entered.

In [134… arr

array([[ 24, 96, 25, 34, 103],


Out[134]:
[ 33, 28, 31, 71, 86],
[101, 33, 9, 19, 100],
[ 43, 71, 87, 19, 85],
[ 82, 7, 4, 45, 63]])

In [135… np.full_like(arr , 22)

array([[22, 22, 22, 22, 22],


Out[135]:
[22, 22, 22, 22, 22],
[22, 22, 22, 22, 22],
[22, 22, 22, 22, 22],
[22, 22, 22, 22, 22]])

In [137… np.full_like(arr , 23)

array([[23, 23, 23, 23, 23],


Out[137]:
[23, 23, 23, 23, 23],
[23, 23, 23, 23, 23],
[23, 23, 23, 23, 23],
[23, 23, 23, 23, 23]])

np.diagonal()
It returns an array diagonal principal from an array.
By default , function value of offset = 0

In [126… arr = np.random.randint(1,122,25)


arr

array([ 24, 96, 25, 34, 103, 33, 28, 31, 71, 86, 101, 33, 9,
Out[126]:
19, 100, 43, 71, 87, 19, 85, 82, 7, 4, 45, 63])

In [127… arr = arr.reshape(5,5)


arr

array([[ 24, 96, 25, 34, 103],


Out[127]:
[ 33, 28, 31, 71, 86],
[101, 33, 9, 19, 100],
[ 43, 71, 87, 19, 85],
[ 82, 7, 4, 45, 63]])

In [128… np.diagonal(arr)

array([24, 28, 9, 19, 63])


Out[128]:

In [129… np.diagonal(arr , offset=1)

array([96, 31, 19, 85])


Out[129]:

In [130… np.diagonal(arr , offset=-1)

localhost:8888/doc/tree/OneDrive/Desktop/PYTHON'S FILES/NUMPY.ipynb 10/80


1/13/24, 10:51 AM NUMPY
array([33, 33, 87, 45])
Out[130]:

In [131… np.diagonal(arr , offset=0)

array([24, 28, 9, 19, 63])


Out[131]:

In [132… np.diagonal( arr , offset=2)

array([ 25, 71, 100])


Out[132]:

In [133… np.diagonal( arr , offset=-2)

array([101, 71, 4])


Out[133]:

np.diag()
It creates an diagonal array.
In a diagonal array, the diagonal elements are non-zero rest every element is zero

Syntax:-

np.diag([diagonal])

In [141… arr1 = np.diag([1,2,3,4,5])


arr1

array([[1, 0, 0, 0, 0],
Out[141]:
[0, 2, 0, 0, 0],
[0, 0, 3, 0, 0],
[0, 0, 0, 4, 0],
[0, 0, 0, 0, 5]])

In [139… arr1.T

array([[1, 0, 0, 0, 0],
Out[139]:
[0, 2, 0, 0, 0],
[0, 0, 3, 0, 0],
[0, 0, 0, 4, 0],
[0, 0, 0, 0, 5]])

In [142… arr2 = np.diag([[1,2,3,4,5] , [6,7,89,8,9]])


arr2

array([1, 7])
Out[142]:

In [143… arr2.T

array([1, 7])
Out[143]:

In [144… arr3 = np.diag([[1,2,3] , [4,5,6] , [7,8,9]])


arr3

array([1, 5, 9])
Out[144]:

localhost:8888/doc/tree/OneDrive/Desktop/PYTHON'S FILES/NUMPY.ipynb 11/80


1/13/24, 10:51 AM NUMPY

In [145… arr3.T

array([1, 5, 9])
Out[145]:

In [23]: np.random.seed(1)
arr1 = np.random.randint(1,50,16)
print(arr1)
print("--------------------------------------------------------------------------")
print(arr1.reshape(4,4))

[38 44 13 9 10 12 6 16 1 17 2 13 8 46 7 26]
--------------------------------------------------------------------------
[[38 44 13 9]
[10 12 6 16]
[ 1 17 2 13]
[ 8 46 7 26]]

random.seed() function use for seeding the value at one time only because random.randint
gives new values every time you run the cell so it is used to stop that regular changingvalues.

In [3]: a = np.random.randint(1,20,16)
a

array([16, 14, 2, 9, 7, 1, 5, 5, 19, 14, 8, 13, 10, 3, 1, 5])


Out[3]:

In [4]: numpyyy = a.reshape(4,4)


numpyyy

array([[16, 14, 2, 9],


Out[4]:
[ 7, 1, 5, 5],
[19, 14, 8, 13],
[10, 3, 1, 5]])

In [5]: np.diagonal(numpyyy)

array([16, 1, 8, 5])
Out[5]:

In [6]: print(np.diagonal(numpyyy, offset=0))


print(np.diagonal(numpyyy , offset=1))
print(np.diagonal(numpyyy , offset=-1))
print(np.diagonal(numpyyy , offset=2))
print(np.diagonal(numpyyy , offset=-2))

[16 1 8 5]
[14 5 13]
[ 7 14 1]
[2 5]
[19 3]

In [7]: np.diag(numpyyy)

array([16, 1, 8, 5])
Out[7]:

In [8]: x = np.arange(9).reshape(3,3)
x

localhost:8888/doc/tree/OneDrive/Desktop/PYTHON'S FILES/NUMPY.ipynb 12/80


1/13/24, 10:51 AM NUMPY
array([[0, 1, 2],
Out[8]:
[3, 4, 5],
[6, 7, 8]])

In [9]: print(np.diag(x))
print(np.diag(x, k=1))
print(np.diag(x, k=-1))

[0 4 8]
[1 5]
[3 7]

np.trace()
It gives the sum of diagonals of array.

In [10]: numpyyy

array([[16, 14, 2, 9],


Out[10]:
[ 7, 1, 5, 5],
[19, 14, 8, 13],
[10, 3, 1, 5]])

In [11]: np.trace(numpyyy)

30
Out[11]:

In [12]: 19+15+1+2

37
Out[12]:

In [13]: np.trace(numpyyy,offset=1)

32
Out[13]:

In [14]: 6+19+14

39
Out[14]:

In [15]: #As you can see it gives values between 0 and 1 whichever value you entered.

np.random.rand(2)

array([0.06796111, 0.86749409])
Out[15]:

In [16]: np.random.randn(21)

array([-0.40622342, 0.1723978 , -0.51049901, 1.30585644, -0.07427142,


Out[16]:
1.05716872, -0.11081497, 0.51242269, -0.57330986, -1.01703679,
0.37237331, 0.57008987, 0.08343948, 0.68627796, -0.27789231,
1.20125542, 0.6408641 , -0.17652394, -0.06708326, 0.36646244,
-0.82416616])

In [50]: np.random.random_integers(1,22)

localhost:8888/doc/tree/OneDrive/Desktop/PYTHON'S FILES/NUMPY.ipynb 13/80


1/13/24, 10:51 AM NUMPY

C:\Users\hp\AppData\Local\Temp\ipykernel_7640\3284952165.py:1: DeprecationWarning: Th
is function is deprecated. Please call randint(1, 22 + 1) instead
np.random.random_integers(1,22)
8
Out[50]:

Attributes Description

ndim - returns number of dimension of the array


size - returns number of elements in the array
dtype - returns data type of elements in the array
shape - returns the size of the array in each dimension.
itemsize - returns the size (in bytes) of each elements in the array
data - returns the buffer containing actual elements of the array in memory

shape()
This tell us about the shape of array.
It tells us about the columns and rows. first it will tell about the columns then rows.

In [54]: arr1 = np.random.randint(1,22,20)


arr1

array([18, 19, 2, 21, 11, 1, 8, 1, 20, 18, 15, 14, 21, 21, 12, 7, 14,
Out[54]:
16, 10, 3])

In [55]: arr1.shape

(20,)
Out[55]:

In [17]: numpyyy

array([[16, 14, 2, 9],


Out[17]:
[ 7, 1, 5, 5],
[19, 14, 8, 13],
[10, 3, 1, 5]])

In [57]: numpyyy.shape

(4, 4)
Out[57]:

In [23]: a

array([16, 14, 2, 9, 7, 1, 5, 5, 19, 14, 8, 13, 10, 3, 1, 5])


Out[23]:

In [24]: print(a.shape)
print(a.itemsize)
print(a.data)

(16,)
4
<memory at 0x0000026E45289180>

In [21]: numpyyy.itemsize

localhost:8888/doc/tree/OneDrive/Desktop/PYTHON'S FILES/NUMPY.ipynb 14/80


1/13/24, 10:51 AM NUMPY
4
Out[21]:

In [19]: numpyyy.data

<memory at 0x0000026E45A6CA00>
Out[19]:

As you can see in upper codes it is giving columns first then rows

Reshape
It reshapes the array as per the shape we have passed
It return a new array of the given shape, it doesnot make the changes in the existing array

In [27]: a

array([16, 14, 2, 9, 7, 1, 5, 5, 19, 14, 8, 13, 10, 3, 1, 5])


Out[27]:

In [28]: a.reshape(2,2,4)

array([[[16, 14, 2, 9],


Out[28]:
[ 7, 1, 5, 5]],

[[19, 14, 8, 13],


[10, 3, 1, 5]]])

In [29]: a.reshape(4,2,2)

array([[[16, 14],
Out[29]:
[ 2, 9]],

[[ 7, 1],
[ 5, 5]],

[[19, 14],
[ 8, 13]],

[[10, 3],
[ 1, 5]]])

In [30]: a.itemsize

4
Out[30]:

In [7]: np.size(a)

16
Out[7]:

In this upper code (2,2,4) and (4,2,2) reliee on this concept


number of layers, list in each layer, elements in each list

dtype()

localhost:8888/doc/tree/OneDrive/Desktop/PYTHON'S FILES/NUMPY.ipynb 15/80


1/13/24, 10:51 AM NUMPY

dtype tells us about what type of data in the array.

In [64]: numpyyy

array([[19, 6, 19, 12],


Out[64]:
[11, 15, 19, 5],
[10, 18, 1, 14],
[10, 10, 8, 2]])

In [65]: numpyyy.dtype

dtype('int32')
Out[65]:

In [66]: a

array([19, 6, 19, 12, 11, 15, 19, 5, 10, 18, 1, 14, 10, 10, 8, 2])
Out[66]:

In [67]: a.dtype

dtype('int32')
Out[67]:

In [72]: b = np.full((4,3), "lavish" )


b

array([['lavish', 'lavish', 'lavish'],


Out[72]:
['lavish', 'lavish', 'lavish'],
['lavish', 'lavish', 'lavish'],
['lavish', 'lavish', 'lavish']], dtype='<U6')

In [73]: b.dtype

dtype('<U6')
Out[73]:

In [74]: b = np.full((4,3), "lavish" , dtype = 'object')


b

array([['lavish', 'lavish', 'lavish'],


Out[74]:
['lavish', 'lavish', 'lavish'],
['lavish', 'lavish', 'lavish'],
['lavish', 'lavish', 'lavish']], dtype=object)

In [75]: b.dtype

dtype('O')
Out[75]:

ndim() - Dimensionality
It tell us about the dimensions of array.

In [76]: a

array([19, 6, 19, 12, 11, 15, 19, 5, 10, 18, 1, 14, 10, 10, 8, 2])
Out[76]:

In [77]: a.ndim

localhost:8888/doc/tree/OneDrive/Desktop/PYTHON'S FILES/NUMPY.ipynb 16/80


1/13/24, 10:51 AM NUMPY
1
Out[77]:

In [78]: numpyyy

array([[19, 6, 19, 12],


Out[78]:
[11, 15, 19, 5],
[10, 18, 1, 14],
[10, 10, 8, 2]])

In [79]: numpyyy.ndim

2
Out[79]:

In [80]: b

array([['lavish', 'lavish', 'lavish'],


Out[80]:
['lavish', 'lavish', 'lavish'],
['lavish', 'lavish', 'lavish'],
['lavish', 'lavish', 'lavish']], dtype=object)

In [82]: b.ndim

2
Out[82]:

In [91]: arr1 = np.array([[[1,2,3,4],[5,6,7,8],


[2,3,4,5],[56,6,7,8]]])
arr1

array([[[ 1, 2, 3, 4],
Out[91]:
[ 5, 6, 7, 8],
[ 2, 3, 4, 5],
[56, 6, 7, 8]]])

In [92]: arr1.ndim

3
Out[92]:

In [95]: num = np.random.randint(1,50,25).reshape(5,5)


num

array([[20, 25, 43, 21, 45],


Out[95]:
[16, 31, 28, 15, 20],
[27, 44, 23, 8, 36],
[48, 47, 35, 37, 37],
[33, 20, 4, 25, 20]])

In [96]: num.ndim

2
Out[96]:

In [97]: num1 = np.random.randint(1,40,24).reshape(2,3,4)


num1

localhost:8888/doc/tree/OneDrive/Desktop/PYTHON'S FILES/NUMPY.ipynb 17/80


1/13/24, 10:51 AM NUMPY
array([[[38, 31, 39, 6],
Out[97]:
[16, 24, 33, 11],
[ 3, 25, 35, 31]],

[[18, 5, 1, 15],
[18, 36, 18, 29],
[23, 39, 11, 14]]])

In [98]: num1.ndim

3
Out[98]:

In [104… num2 = np.random.randint(1,40,36).reshape(2,3,3,2)


num2

array([[[[37, 17],
Out[104]:
[31, 21],
[36, 18]],

[[ 3, 22],
[30, 37],
[17, 28]],

[[ 9, 29],
[ 3, 36],
[14, 37]]],

[[[37, 19],
[34, 39],
[26, 38]],

[[ 3, 35],
[29, 15],
[12, 27]],

[[22, 17],
[29, 38],
[12, 23]]]])

In [105… num2.ndim

4
Out[105]:

How to Create a 2D array and 3D array


In [107… arr = np.array([[1,2,3,4,5],[7,8,9,0,2]])
arr

array([[1, 2, 3, 4, 5],
Out[107]:
[7, 8, 9, 0, 2]])

In [111… arr.ndim

2
Out[111]:

localhost:8888/doc/tree/OneDrive/Desktop/PYTHON'S FILES/NUMPY.ipynb 18/80


1/13/24, 10:51 AM NUMPY

In [115… arr1 = np.array([[[1,2,3,4],[2,3,4,5]],[[3,4,5,6],[5,6,7,8]]])


arr1

array([[[1, 2, 3, 4],
Out[115]:
[2, 3, 4, 5]],

[[3, 4, 5, 6],
[5, 6, 7, 8]]])

In [116… arr1.ndim

3
Out[116]:

Indexing and Slicing in Array


Indexing and Slicing in 1-D array
the indexing and the slicing of a 1-D array is similar to the indexing and the slicing of a list
Array will support both Positive and negative indexing

Indexing and Slicing in 2-D array


How many list are there in an array and how many elements are there in each list
How many list out of the total we want and how many elements from the total we want

Indexing
Fetching the elements out form a particular position or index

Syntax:

arr[index]

In [167… numpyyy

array([[52, 6, 52, 12],


Out[167]:
[11, 15, 19, 5],
[10, 18, 1, 14],
[10, 10, 8, 2]])

In [166… print(numpyyy[0])
print(numpyyy[1])
print(numpyyy[-1])
print(numpyyy[-2])
print(numpyyy[0][0])
print(numpyyy[-1][-1])
print(numpyyy[len(numpyyy)-1])
print(numpyyy[len(numpyyy)-1][-2])
print(numpyyy[2][3])
print(numpyyy[2][0])

localhost:8888/doc/tree/OneDrive/Desktop/PYTHON'S FILES/NUMPY.ipynb 19/80


1/13/24, 10:51 AM NUMPY
[52 6 52 12]
[11 15 19 5]
[10 10 8 2]
[10 18 1 14]
52
2
[10 10 8 2]
8
14
10

In [169… numpyyy[2,0] = 55

In [170… numpyyy

array([[52, 6, 52, 12],


Out[170]:
[11, 15, 19, 5],
[55, 18, 1, 14],
[10, 10, 8, 2]])

In [161… np.random.seed(1)
arr1 = np.random.randint(1,50,24)
arr1

array([38, 44, 13, 9, 10, 12, 6, 16, 1, 17, 2, 13, 8, 46, 7, 26, 21,
Out[161]:
38, 19, 21, 12, 43, 29, 30])

In [162… arr = arr1.reshape(4,6)


arr

array([[38, 44, 13, 9, 10, 12],


Out[162]:
[ 6, 16, 1, 17, 2, 13],
[ 8, 46, 7, 26, 21, 38],
[19, 21, 12, 43, 29, 30]])

In [163… arr.ndim

2
Out[163]:

In [168… len(arr)

4
Out[168]:

In [171… arr

array([[38, 44, 13, 9, 10, 12],


Out[171]:
[ 6, 16, 1, 17, 2, 13],
[ 8, 46, 7, 26, 21, 38],
[19, 21, 12, 43, 29, 30]])

In [172… arr[1,4]

2
Out[172]:

Slicing :
rows Slicing :

localhost:8888/doc/tree/OneDrive/Desktop/PYTHON'S FILES/NUMPY.ipynb 20/80


1/13/24, 10:51 AM NUMPY

variable[row_startingindex : row_endingindex : step_size]

Columns Slicing :
variable[column_startindex : column_endingindex : step_size]

Rows and columns Slicing :


variable[row_startingindex : row_endingindex : step_size , column_startindex :
column_endingindex : step_size]

startingindex = 0 (By default)

endingindex = Exclusive (len(variable)+1)

step_size = 0

In [173… arr

array([[38, 44, 13, 9, 10, 12],


Out[173]:
[ 6, 16, 1, 17, 2, 13],
[ 8, 46, 7, 26, 21, 38],
[19, 21, 12, 43, 29, 30]])

In [177… print(arr[0])
print("----------------------")
print(arr[-1])
print("----------------------")
print(arr[::1])
print("----------------------")
print(arr[::-1])

[38 44 13 9 10 12]
----------------------
[19 21 12 43 29 30]
----------------------
[[38 44 13 9 10 12]
[ 6 16 1 17 2 13]
[ 8 46 7 26 21 38]
[19 21 12 43 29 30]]
----------------------
[[19 21 12 43 29 30]
[ 8 46 7 26 21 38]
[ 6 16 1 17 2 13]
[38 44 13 9 10 12]]

In [180… print(arr[0:2:])
print("----------------------")
print(arr[:len(arr):])

[[38 44 13 9 10 12]
[ 6 16 1 17 2 13]]
----------------------
[[38 44 13 9 10 12]
[ 6 16 1 17 2 13]
[ 8 46 7 26 21 38]
[19 21 12 43 29 30]]

localhost:8888/doc/tree/OneDrive/Desktop/PYTHON'S FILES/NUMPY.ipynb 21/80


1/13/24, 10:51 AM NUMPY

In [190… print(arr[::,::])
print("----------------------")
print(arr[1:3:,::])

[[38 44 13 9 10 12]
[ 6 16 1 17 2 13]
[ 8 46 7 26 21 38]
[19 21 12 43 29 30]]
----------------------
[[ 6 16 1 17 2 13]
[ 8 46 7 26 21 38]]

In [187… print(arr[:2:,:5:])
print("----------------------")
print(arr[:2:,:1:])

[[38 44 13 9 10]
[ 6 16 1 17 2]]
----------------------
[[38]
[ 6]]

In [193… print(arr[::,::])
print("----------------------")
print(arr[2:4:,2:-1:])

[[38 44 13 9 10 12]
[ 6 16 1 17 2 13]
[ 8 46 7 26 21 38]
[19 21 12 43 29 30]]
----------------------
[[ 7 26 21]
[12 43 29]]

In [194… print(arr[::,::])
print("----------------------")
print(arr[2::,:2:])

[[38 44 13 9 10 12]
[ 6 16 1 17 2 13]
[ 8 46 7 26 21 38]
[19 21 12 43 29 30]]
----------------------
[[ 8 46]
[19 21]]

In [195… print(arr[::,::])
print("----------------------")
print(arr[1::,2:3:])

[[38 44 13 9 10 12]
[ 6 16 1 17 2 13]
[ 8 46 7 26 21 38]
[19 21 12 43 29 30]]
----------------------
[[ 1]
[ 7]
[12]]

In [196… print(arr[::,::])
print("----------------------")
localhost:8888/doc/tree/OneDrive/Desktop/PYTHON'S FILES/NUMPY.ipynb 22/80
1/13/24, 10:51 AM NUMPY
print(arr[::,5::])

[[38 44 13 9 10 12]
[ 6 16 1 17 2 13]
[ 8 46 7 26 21 38]
[19 21 12 43 29 30]]
----------------------
[[12]
[13]
[38]
[30]]

In [200… print(arr[::,::])
print("----------------------")
print(arr[::-1,5:len(arr):-1])

[[38 44 13 9 10 12]
[ 6 16 1 17 2 13]
[ 8 46 7 26 21 38]
[19 21 12 43 29 30]]
----------------------
[[30]
[38]
[13]
[12]]

In [201… np.random.seed(1)
arr2 = np.random.randint(22,222,81).reshape(9,9)
arr2

array([[ 59, 162, 94, 159, 155, 101, 214, 166, 151],
Out[201]:
[ 93, 156, 47, 200, 42, 123, 168, 161, 178],
[179, 164, 72, 90, 118, 108, 163, 159, 29],
[ 85, 83, 44, 79, 23, 150, 82, 30, 163],
[137, 197, 143, 52, 93, 153, 220, 171, 71],
[ 79, 25, 218, 46, 65, 98, 48, 74, 102],
[131, 137, 63, 37, 86, 218, 47, 133, 157],
[ 48, 175, 126, 44, 31, 217, 148, 45, 147],
[122, 177, 187, 79, 105, 188, 158, 54, 184]])

In [205… print(arr2[::,::])
print("----------------------")
print(arr2[:: ,8:len(arr2):])

localhost:8888/doc/tree/OneDrive/Desktop/PYTHON'S FILES/NUMPY.ipynb 23/80


1/13/24, 10:51 AM NUMPY
[[ 59 162 94 159 155 101 214 166 151]
[ 93 156 47 200 42 123 168 161 178]
[179 164 72 90 118 108 163 159 29]
[ 85 83 44 79 23 150 82 30 163]
[137 197 143 52 93 153 220 171 71]
[ 79 25 218 46 65 98 48 74 102]
[131 137 63 37 86 218 47 133 157]
[ 48 175 126 44 31 217 148 45 147]
[122 177 187 79 105 188 158 54 184]]
----------------------
[[151]
[178]
[ 29]
[163]
[ 71]
[102]
[157]
[147]
[184]]

In [207… print(arr2[::,::])
print("--------------------------------------------------------")
print(arr2[::-1,8:len(arr2):])

[[ 59 162 94 159 155 101 214 166 151]


[ 93 156 47 200 42 123 168 161 178]
[179 164 72 90 118 108 163 159 29]
[ 85 83 44 79 23 150 82 30 163]
[137 197 143 52 93 153 220 171 71]
[ 79 25 218 46 65 98 48 74 102]
[131 137 63 37 86 218 47 133 157]
[ 48 175 126 44 31 217 148 45 147]
[122 177 187 79 105 188 158 54 184]]
--------------------------------------------------------
[[184]
[147]
[157]
[102]
[ 71]
[163]
[ 29]
[178]
[151]]

In [215… print(arr2[::,::])
print("----------------------------------------------")
print(arr2[::-1,4:5:])

localhost:8888/doc/tree/OneDrive/Desktop/PYTHON'S FILES/NUMPY.ipynb 24/80


1/13/24, 10:51 AM NUMPY
[[ 59 162 94 159 155 101 214 166 151]
[ 93 156 47 200 42 123 168 161 178]
[179 164 72 90 118 108 163 159 29]
[ 85 83 44 79 23 150 82 30 163]
[137 197 143 52 93 153 220 171 71]
[ 79 25 218 46 65 98 48 74 102]
[131 137 63 37 86 218 47 133 157]
[ 48 175 126 44 31 217 148 45 147]
[122 177 187 79 105 188 158 54 184]]
----------------------------------------------
[[105]
[ 31]
[ 86]
[ 65]
[ 93]
[ 23]
[118]
[ 42]
[155]]

In [217… print(arr2[::,::])
print("----------------------------------------------")
print(arr2[::,6:7:])

[[ 59 162 94 159 155 101 214 166 151]


[ 93 156 47 200 42 123 168 161 178]
[179 164 72 90 118 108 163 159 29]
[ 85 83 44 79 23 150 82 30 163]
[137 197 143 52 93 153 220 171 71]
[ 79 25 218 46 65 98 48 74 102]
[131 137 63 37 86 218 47 133 157]
[ 48 175 126 44 31 217 148 45 147]
[122 177 187 79 105 188 158 54 184]]
----------------------------------------------
[[214]
[168]
[163]
[ 82]
[220]
[ 48]
[ 47]
[148]
[158]]

In [233… print(arr2[::,::])
print("----------------------------------------------")
print(np.diagonal(arr2)[::])
print("----------------------------------------------")
print(np.diagonal(arr2)[::-1])
print("----------------------------------------------")
print(np.diagonal(arr2, offset=1)[::])
print("----------------------------------------------")
print(np.diagonal(arr2, offset=-1)[::])
print("----------------------------------------------")
print(np.diag(arr2 , k=6)[::])
print("----------------------------------------------")
print(np.diagonal(arr2 , offset=8)[::])

localhost:8888/doc/tree/OneDrive/Desktop/PYTHON'S FILES/NUMPY.ipynb 25/80


1/13/24, 10:51 AM NUMPY
[[ 59 162 94 159 155 101 214 166 151]
[ 93 156 47 200 42 123 168 161 178]
[179 164 72 90 118 108 163 159 29]
[ 85 83 44 79 23 150 82 30 163]
[137 197 143 52 93 153 220 171 71]
[ 79 25 218 46 65 98 48 74 102]
[131 137 63 37 86 218 47 133 157]
[ 48 175 126 44 31 217 148 45 147]
[122 177 187 79 105 188 158 54 184]]
----------------------------------------------
[ 59 156 72 79 93 98 47 45 184]
----------------------------------------------
[184 45 47 98 93 79 72 156 59]
----------------------------------------------
[162 47 90 23 153 48 133 147]
----------------------------------------------
[ 93 164 44 52 65 218 148 54]
----------------------------------------------
[214 161 29]
----------------------------------------------
[151]

You're on the right track – np.diagonals is well suited for this, but you need to take care
computing the offsets. In numpy (and in matrix math by convention) the diagonals run {{top-
left to bottom-right.}} The main diagonal has offset 0; the diagonals above this have positive
offsets, and the diagonals below have negative offsets.

In [234… arr2

array([[ 59, 162, 94, 159, 155, 101, 214, 166, 151],
Out[234]:
[ 93, 156, 47, 200, 42, 123, 168, 161, 178],
[179, 164, 72, 90, 118, 108, 163, 159, 29],
[ 85, 83, 44, 79, 23, 150, 82, 30, 163],
[137, 197, 143, 52, 93, 153, 220, 171, 71],
[ 79, 25, 218, 46, 65, 98, 48, 74, 102],
[131, 137, 63, 37, 86, 218, 47, 133, 157],
[ 48, 175, 126, 44, 31, 217, 148, 45, 147],
[122, 177, 187, 79, 105, 188, 158, 54, 184]])

In [235… np.diag(arr2)

array([ 59, 156, 72, 79, 93, 98, 47, 45, 184])
Out[235]:

In [236… np.diag(np.diag(arr2))

array([[ 59, 0, 0, 0, 0, 0, 0, 0, 0],


Out[236]:
[ 0, 156, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 72, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 79, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 93, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 98, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 47, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 45, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 184]])

In [5]: arr1 = np.random.randint(30,70,121).reshape(11,11)


arr1

localhost:8888/doc/tree/OneDrive/Desktop/PYTHON'S FILES/NUMPY.ipynb 26/80


1/13/24, 10:51 AM NUMPY
array([[60, 66, 69, 63, 45, 61, 49, 45, 69, 31, 67],
Out[5]:
[64, 50, 64, 53, 69, 44, 56, 45, 56, 58, 50],
[32, 34, 45, 36, 59, 55, 66, 45, 59, 69, 64],
[52, 59, 66, 41, 31, 43, 41, 50, 69, 53, 46],
[65, 35, 56, 62, 51, 37, 45, 61, 59, 42, 46],
[61, 59, 69, 59, 34, 38, 53, 49, 48, 63, 59],
[59, 38, 69, 57, 69, 49, 45, 64, 41, 49, 55],
[36, 69, 34, 35, 51, 33, 67, 58, 62, 50, 40],
[46, 62, 54, 32, 37, 58, 37, 34, 42, 54, 54],
[30, 31, 44, 32, 64, 44, 33, 41, 62, 31, 48],
[57, 44, 54, 33, 32, 66, 49, 67, 36, 41, 47]])

In [4]: np.diag(np.diag(arr1))

array([[47, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
Out[4]:
[ 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 40, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 56, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 48, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 63, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 54, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 56, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 31, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 30, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 33]])

In [6]: arr1

array([[60, 66, 69, 63, 45, 61, 49, 45, 69, 31, 67],
Out[6]:
[64, 50, 64, 53, 69, 44, 56, 45, 56, 58, 50],
[32, 34, 45, 36, 59, 55, 66, 45, 59, 69, 64],
[52, 59, 66, 41, 31, 43, 41, 50, 69, 53, 46],
[65, 35, 56, 62, 51, 37, 45, 61, 59, 42, 46],
[61, 59, 69, 59, 34, 38, 53, 49, 48, 63, 59],
[59, 38, 69, 57, 69, 49, 45, 64, 41, 49, 55],
[36, 69, 34, 35, 51, 33, 67, 58, 62, 50, 40],
[46, 62, 54, 32, 37, 58, 37, 34, 42, 54, 54],
[30, 31, 44, 32, 64, 44, 33, 41, 62, 31, 48],
[57, 44, 54, 33, 32, 66, 49, 67, 36, 41, 47]])

In [8]: np.diagflat(np.diagflat(arr1))

array([[60, 0, 0, ..., 0, 0, 0],


Out[8]:
[ 0, 0, 0, ..., 0, 0, 0],
[ 0, 0, 0, ..., 0, 0, 0],
...,
[ 0, 0, 0, ..., 0, 0, 0],
[ 0, 0, 0, ..., 0, 0, 0],
[ 0, 0, 0, ..., 0, 0, 47]])

diagflat() :
It creates the diagonals from given array and rest of non diagonal values becomes 0's.

In [11]: numm = np.diagflat([[22,23,2,4],[11,13,12,1]])


numm

localhost:8888/doc/tree/OneDrive/Desktop/PYTHON'S FILES/NUMPY.ipynb 27/80


1/13/24, 10:51 AM NUMPY
array([[22, 0, 0, 0, 0, 0, 0, 0],
Out[11]:
[ 0, 23, 0, 0, 0, 0, 0, 0],
[ 0, 0, 2, 0, 0, 0, 0, 0],
[ 0, 0, 0, 4, 0, 0, 0, 0],
[ 0, 0, 0, 0, 11, 0, 0, 0],
[ 0, 0, 0, 0, 0, 13, 0, 0],
[ 0, 0, 0, 0, 0, 0, 12, 0],
[ 0, 0, 0, 0, 0, 0, 0, 1]])

In [12]: numm.ndim

2
Out[12]:

In [19]: x = np.diagflat([[[12,12],[22,22],
[33,33],[44,44]]])
x

array([[12, 0, 0, 0, 0, 0, 0, 0],
Out[19]:
[ 0, 12, 0, 0, 0, 0, 0, 0],
[ 0, 0, 22, 0, 0, 0, 0, 0],
[ 0, 0, 0, 22, 0, 0, 0, 0],
[ 0, 0, 0, 0, 33, 0, 0, 0],
[ 0, 0, 0, 0, 0, 33, 0, 0],
[ 0, 0, 0, 0, 0, 0, 44, 0],
[ 0, 0, 0, 0, 0, 0, 0, 44]])

In [20]: x.ndim

2
Out[20]:

In [21]: x = np.diagonal([[[12,12],[22,22],
[33,33],[44,44]]])
x

array([[12],
Out[21]:
[12]])

In [24]: x = np.diag([[[12,12],[22,22],
[33,33],[44,44]]])
x

---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[24], line 1
----> 1 x = np.diag([[[12,12],[22,22],
2 [33,33],[44,44]]])
3 x

File <__array_function__ internals>:200, in diag(*args, **kwargs)

File ~\anaconda3\Lib\site-packages\numpy\lib\twodim_base.py:309, in diag(v, k)


307 return diagonal(v, k)
308 else:
--> 309 raise ValueError("Input must be 1- or 2-d.")

ValueError: Input must be 1- or 2-d.

localhost:8888/doc/tree/OneDrive/Desktop/PYTHON'S FILES/NUMPY.ipynb 28/80


1/13/24, 10:51 AM NUMPY

As you can see in above codes np.diag and np.diagonal doesn't create a array
by giving arrays it is only applicable in np.diagflat

In [25]: arr = np.random.random(9).reshape(3,3)


arr

array([[0.48998727, 0.05287216, 0.6760068 ],


Out[25]:
[0.21407884, 0.41751812, 0.16895348],
[0.11383233, 0.06469908, 0.70521954]])

In [26]: arr1 = np.random.rand(3,4)


arr1

array([[0.15206723, 0.91247594, 0.27013392, 0.36346606],


Out[26]:
[0.81680048, 0.97292427, 0.61096113, 0.13051703],
[0.46627602, 0.09510123, 0.49002573, 0.05610081]])

In [29]: np.random.seed(6)
arr3 = np.random.randint(1,200,64).reshape(8,8)
arr3

array([[139, 107, 110, 80, 107, 81, 63, 26],


Out[29]:
[ 2, 76, 78, 186, 27, 162, 111, 69],
[162, 9, 131, 32, 195, 134, 126, 155],
[ 16, 87, 115, 172, 198, 178, 133, 63],
[ 81, 195, 128, 67, 64, 148, 86, 125],
[ 29, 44, 58, 134, 51, 27, 79, 120],
[ 41, 198, 71, 64, 11, 68, 86, 140],
[130, 83, 164, 151, 42, 124, 106, 25]])

Indexing and Slicing in 3-D Array


Indexing :
Syntax :

arr[arr_index] --- It fetches the layer

arr[arr_index , arr_row] ---- It fetches the layer and the list

arr[arr_index , arr_row , arr_column] ---- It fetches layer


and thelist and the elements inside lists.

In [6]: import numpy as np

np.random.seed(1)
arr1 = np.random.randint(30,70,48).reshape(3,4,4)
arr1

localhost:8888/doc/tree/OneDrive/Desktop/PYTHON'S FILES/NUMPY.ipynb 29/80


1/13/24, 10:51 AM NUMPY
array([[[67, 42, 38, 39],
Out[6]:
[41, 35, 45, 30],
[46, 31, 42, 37],
[36, 55, 50, 67]],

[[48, 50, 41, 58],


[59, 44, 34, 53],
[53, 60, 62, 52],
[43, 39, 37, 52]],

[[31, 30, 47, 38],


[54, 43, 38, 60],
[37, 33, 36, 51],
[33, 34, 54, 42]]])

In [7]: arr1[0]

array([[67, 42, 38, 39],


Out[7]:
[41, 35, 45, 30],
[46, 31, 42, 37],
[36, 55, 50, 67]])

In [8]: arr1[0,2] = 22

In [9]: arr1

array([[[67, 42, 38, 39],


Out[9]:
[41, 35, 45, 30],
[22, 22, 22, 22],
[36, 55, 50, 67]],

[[48, 50, 41, 58],


[59, 44, 34, 53],
[53, 60, 62, 52],
[43, 39, 37, 52]],

[[31, 30, 47, 38],


[54, 43, 38, 60],
[37, 33, 36, 51],
[33, 34, 54, 42]]])

In [12]: arr1[0,2,(1,2)] = 11,12


arr1

array([[[67, 42, 38, 39],


Out[12]:
[41, 35, 45, 30],
[22, 11, 12, 22],
[36, 55, 50, 67]],

[[48, 50, 41, 58],


[59, 44, 34, 53],
[53, 60, 62, 52],
[43, 39, 37, 52]],

[[31, 30, 47, 38],


[54, 43, 38, 60],
[37, 33, 36, 51],
[33, 34, 54, 42]]])

localhost:8888/doc/tree/OneDrive/Desktop/PYTHON'S FILES/NUMPY.ipynb 30/80


1/13/24, 10:51 AM NUMPY

In [13]: arr1[2,2,(0,3)] =73,63


arr1

array([[[67, 42, 38, 39],


Out[13]:
[41, 35, 45, 30],
[22, 11, 12, 22],
[36, 55, 50, 67]],

[[48, 50, 41, 58],


[59, 44, 34, 53],
[53, 60, 62, 52],
[43, 39, 37, 52]],

[[31, 30, 47, 38],


[54, 43, 38, 60],
[73, 33, 36, 63],
[33, 34, 54, 42]]])

In [14]: arr1[1,2,(2,3)] = 26,25

In [15]: arr1

array([[[67, 42, 38, 39],


Out[15]:
[41, 35, 45, 30],
[22, 11, 12, 22],
[36, 55, 50, 67]],

[[48, 50, 41, 58],


[59, 44, 34, 53],
[53, 60, 26, 25],
[43, 39, 37, 52]],

[[31, 30, 47, 38],


[54, 43, 38, 60],
[73, 33, 36, 63],
[33, 34, 54, 42]]])

Slicing :
Syntax :

arr[layer_startindex : layer_endindex : step_size]

layer_startindex = 0

layer_endindex = Exclusive (by default)

step size = 1 (By default)

In [16]: arr1

localhost:8888/doc/tree/OneDrive/Desktop/PYTHON'S FILES/NUMPY.ipynb 31/80


1/13/24, 10:51 AM NUMPY
array([[[67, 42, 38, 39],
Out[16]:
[41, 35, 45, 30],
[22, 11, 12, 22],
[36, 55, 50, 67]],

[[48, 50, 41, 58],


[59, 44, 34, 53],
[53, 60, 26, 25],
[43, 39, 37, 52]],

[[31, 30, 47, 38],


[54, 43, 38, 60],
[73, 33, 36, 63],
[33, 34, 54, 42]]])

In [17]: arr1[:len(arr1):2]

array([[[67, 42, 38, 39],


Out[17]:
[41, 35, 45, 30],
[22, 11, 12, 22],
[36, 55, 50, 67]],

[[31, 30, 47, 38],


[54, 43, 38, 60],
[73, 33, 36, 63],
[33, 34, 54, 42]]])

In [18]: arr1[::]

array([[[67, 42, 38, 39],


Out[18]:
[41, 35, 45, 30],
[22, 11, 12, 22],
[36, 55, 50, 67]],

[[48, 50, 41, 58],


[59, 44, 34, 53],
[53, 60, 26, 25],
[43, 39, 37, 52]],

[[31, 30, 47, 38],


[54, 43, 38, 60],
[73, 33, 36, 63],
[33, 34, 54, 42]]])

In [19]: arr1[::-1]

array([[[31, 30, 47, 38],


Out[19]:
[54, 43, 38, 60],
[73, 33, 36, 63],
[33, 34, 54, 42]],

[[48, 50, 41, 58],


[59, 44, 34, 53],
[53, 60, 26, 25],
[43, 39, 37, 52]],

[[67, 42, 38, 39],


[41, 35, 45, 30],
[22, 11, 12, 22],
[36, 55, 50, 67]]])

localhost:8888/doc/tree/OneDrive/Desktop/PYTHON'S FILES/NUMPY.ipynb 32/80


1/13/24, 10:51 AM NUMPY

Now,

arr[layer_startindex : layer_endindex : step_size ,


row_startindex : row_endindex : step_size]
startindex = 0

endindex = Exclusive (by default)

step size = 1 (By default)

In [20]: arr1

array([[[67, 42, 38, 39],


Out[20]:
[41, 35, 45, 30],
[22, 11, 12, 22],
[36, 55, 50, 67]],

[[48, 50, 41, 58],


[59, 44, 34, 53],
[53, 60, 26, 25],
[43, 39, 37, 52]],

[[31, 30, 47, 38],


[54, 43, 38, 60],
[73, 33, 36, 63],
[33, 34, 54, 42]]])

In [21]: arr1[:2: , :2:]

array([[[67, 42, 38, 39],


Out[21]:
[41, 35, 45, 30]],

[[48, 50, 41, 58],


[59, 44, 34, 53]]])

In [26]: arr1[2:: , 2:4:]

array([[[73, 33, 36, 63],


Out[26]:
[33, 34, 54, 42]]])

In [30]: arr1[:len(arr1):2 , -1:-3:-1]

array([[[36, 55, 50, 67],


Out[30]:
[22, 11, 12, 22]],

[[33, 34, 54, 42],


[73, 33, 36, 63]]])

In [32]: arr1[2,2]

array([73, 33, 36, 63])


Out[32]:

In [36]: arr1[:2: , -1:-4:-2]

localhost:8888/doc/tree/OneDrive/Desktop/PYTHON'S FILES/NUMPY.ipynb 33/80


1/13/24, 10:51 AM NUMPY
array([[[36, 55, 50, 67],
Out[36]:
[41, 35, 45, 30]],

[[43, 39, 37, 52],


[59, 44, 34, 53]]])

In [37]: arr1

array([[[67, 42, 38, 39],


Out[37]:
[41, 35, 45, 30],
[22, 11, 12, 22],
[36, 55, 50, 67]],

[[48, 50, 41, 58],


[59, 44, 34, 53],
[53, 60, 26, 25],
[43, 39, 37, 52]],

[[31, 30, 47, 38],


[54, 43, 38, 60],
[73, 33, 36, 63],
[33, 34, 54, 42]]])

In [43]: print(arr1[:1: , 1:2:])


print("----------------------------------------------")
print(arr1[:3:2 , 2:3:])
print("----------------------------------------------")
print(arr1[:3:2 , 1:3:])
print("----------------------------------------------")
print(arr1[:3:2 , -2:-4:-1])

[[[41 35 45 30]]]
----------------------------------------------
[[[22 11 12 22]]

[[73 33 36 63]]]
----------------------------------------------
[[[41 35 45 30]
[22 11 12 22]]

[[54 43 38 60]
[73 33 36 63]]]
----------------------------------------------
[[[22 11 12 22]
[41 35 45 30]]

[[73 33 36 63]
[54 43 38 60]]]

In [44]: print(arr1[:: , ::-2])

[[[36 55 50 67]
[41 35 45 30]]

[[43 39 37 52]
[59 44 34 53]]

[[33 34 54 42]
[54 43 38 60]]]

localhost:8888/doc/tree/OneDrive/Desktop/PYTHON'S FILES/NUMPY.ipynb 34/80


1/13/24, 10:51 AM NUMPY

In [45]: print(arr1[:: , ::-3])

[[[36 55 50 67]
[67 42 38 39]]

[[43 39 37 52]
[48 50 41 58]]

[[33 34 54 42]
[31 30 47 38]]]

In [46]: print(arr1[:: ,::-4])

[[[36 55 50 67]]

[[43 39 37 52]]

[[33 34 54 42]]]

Now,
arr[layer_startindex : layer_endindex : step_size , row_startindex :
row_endindex : step_size , column_startindex : column_endindex : step_size]
startindex = 0

endindex = Exclusive (by default)

step size = 1 (By default)

In [48]: arr1

array([[[67, 42, 38, 39],


Out[48]:
[41, 35, 45, 30],
[22, 11, 12, 22],
[36, 55, 50, 67]],

[[48, 50, 41, 58],


[59, 44, 34, 53],
[53, 60, 26, 25],
[43, 39, 37, 52]],

[[31, 30, 47, 38],


[54, 43, 38, 60],
[73, 33, 36, 63],
[33, 34, 54, 42]]])

In [49]: print(arr1[:: , :: , 3::])

localhost:8888/doc/tree/OneDrive/Desktop/PYTHON'S FILES/NUMPY.ipynb 35/80


1/13/24, 10:51 AM NUMPY
[[[39]
[30]
[22]
[67]]

[[58]
[53]
[25]
[52]]

[[38]
[60]
[63]
[42]]]

In [53]: print(arr1[::2 , :2: , 3::])

[[[39]
[30]]

[[38]
[60]]]

In [55]: print(arr1[:2: , 2:: , 1:3:])

[[[11 12]
[55 50]]

[[60 26]
[39 37]]]

In [56]: print(arr1[::2 , 2:: , 1:3:])

[[[11 12]
[55 50]]

[[33 36]
[34 54]]]

In [57]: np.random.seed(1)
varr = np.random.randint(22,172,49).reshape(7,7)
varr

array([[ 59, 162, 94, 159, 155, 101, 166],


Out[57]:
[151, 93, 156, 47, 42, 123, 168],
[161, 164, 72, 90, 118, 108, 163],
[159, 29, 85, 83, 44, 79, 23],
[150, 82, 30, 163, 137, 143, 52],
[ 93, 153, 171, 71, 79, 25, 46],
[ 65, 98, 48, 74, 102, 131, 137]])

In [58]: np.diag(varr)

array([ 59, 93, 72, 83, 137, 25, 137])


Out[58]:

In [60]: np.diag(varr)[::-1]

array([137, 25, 137, 83, 72, 93, 59])


Out[60]:

localhost:8888/doc/tree/OneDrive/Desktop/PYTHON'S FILES/NUMPY.ipynb 36/80


1/13/24, 10:51 AM NUMPY

Now Now Now, You can see in Below code that in diagonal it is possible that
we can extract the diagonal from {right-top-left-bottom}

In [66]: np.diag(varr[::-1])[::]

array([ 65, 153, 30, 83, 118, 123, 166])


Out[66]:

In [67]: np.diag(varr[::-1])[::-1]

array([166, 123, 118, 83, 30, 153, 65])


Out[67]:

Array of Random Value


In numpy, we have a random module that is used to create array of random values in it
##### random.random()
It generates a specified number of random values

The random valuws are always between 0 and 1

Syntax:

np.random.random(number of values)

In [69]: x = np.random.random(24)
x

array([0.41417927, 0.04995346, 0.53589641, 0.66379465, 0.51488911,


Out[69]:
0.94459476, 0.58655504, 0.90340192, 0.1374747 , 0.13927635,
0.80739129, 0.39767684, 0.1653542 , 0.92750858, 0.34776586,
0.7508121 , 0.72599799, 0.88330609, 0.62367221, 0.75094243,
0.34889834, 0.26992789, 0.89588622, 0.42809119])

In [70]: i = np.random.random(36).reshape(3,4,3)
i

array([[[0.96484005, 0.6634415 , 0.62169572],


Out[70]:
[0.11474597, 0.94948926, 0.44991213],
[0.57838961, 0.4081368 , 0.23702698],
[0.90337952, 0.57367949, 0.00287033]],

[[0.61714491, 0.3266449 , 0.5270581 ],


[0.8859421 , 0.35726976, 0.90853515],
[0.62336012, 0.01582124, 0.92943723],
[0.69089692, 0.99732285, 0.17234051]],

[[0.13713575, 0.93259546, 0.69681816],


[0.06600017, 0.75546305, 0.75387619],
[0.92302454, 0.71152476, 0.12427096],
[0.01988013, 0.02621099, 0.02830649]]])

random.randint()
It returns a 1-D array of random numbers (integers) between a specified range

localhost:8888/doc/tree/OneDrive/Desktop/PYTHON'S FILES/NUMPY.ipynb 37/80


1/13/24, 10:51 AM NUMPY

Synatx:

np.random.randint(start, stop, number of values)

By default, both the start and the stop values are excluded

In [71]: v = np.random.randint(1,22,16).reshape(4,4)
v

array([[14, 18, 18, 16],


Out[71]:
[14, 9, 15, 14],
[17, 11, 14, 4],
[21, 3, 15, 15]])

random.seed(random state)
It is used to set the random state of the randomized value
Random state is an integer number in the range 0 to (2**32)-1

In [72]: np.random.seed(10)
arrr = np.random.randint(0,51,36).reshape(6,6)
arrr

array([[ 9, 36, 15, 0, 49, 28],


Out[72]:
[25, 29, 48, 29, 49, 8],
[ 9, 0, 42, 40, 36, 16],
[36, 47, 11, 24, 43, 33],
[ 8, 36, 14, 49, 13, 5],
[13, 25, 13, 28, 22, 30]])

In [74]: np.random.seed(10)
arr1 = np.random.rand(6,6)
arr1

array([[0.77132064, 0.02075195, 0.63364823, 0.74880388, 0.49850701,


Out[74]:
0.22479665],
[0.19806286, 0.76053071, 0.16911084, 0.08833981, 0.68535982,
0.95339335],
[0.00394827, 0.51219226, 0.81262096, 0.61252607, 0.72175532,
0.29187607],
[0.91777412, 0.71457578, 0.54254437, 0.14217005, 0.37334076,
0.67413362],
[0.44183317, 0.43401399, 0.61776698, 0.51313824, 0.65039718,
0.60103895],
[0.8052232 , 0.52164715, 0.90864888, 0.31923609, 0.09045935,
0.30070006]])

In [75]: (2**32)-1

4294967295
Out[75]:

random.normal()
It returns an array of random value those are normally distributed

Syntax: np.random.normal(mean, sd, size)

localhost:8888/doc/tree/OneDrive/Desktop/PYTHON'S FILES/NUMPY.ipynb 38/80


1/13/24, 10:51 AM NUMPY

In [82]: varry = np.random.normal(22, 4 , 50)


varry

array([25.02648743, 19.08240311, 26.8591306 , 26.03313187, 22.29313204,


Out[82]:
26.69492965, 29.45180667, 14.06545401, 26.62675572, 24.43712907,
20.70719507, 24.65658243, 23.58690397, 19.69553256, 27.95287357,
22.56098747, 26.75326702, 21.01701845, 15.45765353, 22.97919235,
21.05967108, 16.95668878, 15.23212828, 24.46580369, 27.07876513,
27.58935191, 24.13689985, 22.01640815, 22.75767937, 22.17909874,
25.1787411 , 20.02743703, 16.95364104, 21.12295894, 22.7890889 ,
20.97887818, 22.10323037, 30.80386575, 25.53747041, 16.45270986,
24.61464926, 13.29356546, 24.4757957 , 23.90893721, 22.10438611,
18.12117731, 18.0650875 , 23.65013086, 19.54278061, 25.3483271 ])

Functions in Array
np.sum()
It returns the sum of the array.

Syntax :

np.sum(arr , axis = 0)
arr.sum(axis = 0,1)

axis = 0 ------> Interpreter reads the array from top to bottom which known as row
wise operation.
axis = 1 ------> Interpreter reads the array from left to right which known as column
wise operation.

In [83]: np.random.seed(1)
axxxiiss = np.random.randint(1,22,14)
axxxiiss

array([ 6, 12, 13, 9, 10, 12, 6, 16, 1, 17, 2, 13, 8, 14])


Out[83]:

In [84]: np.sum(axxxiiss, axis=0)

139
Out[84]:

In [87]: axxxiiss.sum()

139
Out[87]:

In [86]: axxxiiss.sum(axis = 1)

localhost:8888/doc/tree/OneDrive/Desktop/PYTHON'S FILES/NUMPY.ipynb 39/80


1/13/24, 10:51 AM NUMPY

---------------------------------------------------------------------------
AxisError Traceback (most recent call last)
Cell In[86], line 1
----> 1 axxxiiss.sum(axis = 1)

File ~\anaconda3\Lib\site-packages\numpy\core\_methods.py:49, in _sum(a, axis, dtype,


out, keepdims, initial, where)
47 def _sum(a, axis=None, dtype=None, out=None, keepdims=False,
48 initial=_NoValue, where=True):
---> 49 return umr_sum(a, axis, dtype, out, keepdims, initial, where)

AxisError: axis 1 is out of bounds for array of dimension 1

As you can see in upper code is giving error by out of bound for array of 1-D ,

axis = 0,1 is applicable in 2-D , 3-D

In [97]: np.random.seed(1)
i_ = np.random.randint(0,51,16).reshape(4,4)
i_

array([[37, 43, 12, 8],


Out[97]:
[ 9, 11, 5, 15],
[ 0, 16, 1, 12],
[ 7, 45, 6, 25]])

In [103… np.sum(i_ , axis= 0)

array([ 53, 115, 24, 60])


Out[103]:

In [104… i_.sum(axis = 1)

array([100, 40, 29, 83])


Out[104]:

In [100… val = np.random.randint(22,52,16).reshape(2,2,4)


val

array([[[40, 42, 27, 40],


Out[100]:
[42, 33, 50, 32]],

[[50, 51, 36, 40],


[26, 45, 45, 31]]])

In [102… np.sum(val , axis=0)

array([[90, 93, 63, 80],


Out[102]:
[68, 78, 95, 63]])

In [105… np.sum(val , axis = 1)

array([[82, 75, 77, 72],


Out[105]:
[76, 96, 81, 71]])

np.mean()
It returns the average (mean) of the array

Syntax:

localhost:8888/doc/tree/OneDrive/Desktop/PYTHON'S FILES/NUMPY.ipynb 40/80


1/13/24, 10:51 AM NUMPY
np.mean(arr, axis = 0,1)
arr.mean(axis = 0,1

In [106… np.random.seed(1)
arr = np.random.randint(1,51,36).reshape(6,6)
arr

array([[38, 44, 13, 9, 10, 12],


Out[106]:
[ 6, 16, 1, 17, 2, 13],
[ 8, 46, 7, 26, 21, 38],
[19, 21, 12, 43, 29, 30],
[15, 5, 24, 24, 42, 50],
[31, 33, 23, 14, 42, 10]])

In [107… np.mean(arr)

22.055555555555557
Out[107]:

In [109… (38+ 44 + 13 + 9 + 10 + 12 + 6 + 16 + 1 + 17 + 2 + 13 + 8 + 46 + 7
+ 26 + 21 + 38 + 19 + 21 + 12 + 43 + 29 + 30 + 15 + 5 + 24 + 24 + 42 + 50 + 31 + 33 +

22.055555555555557
Out[109]:

To Calculate mean,

Formula : sum of array / no. of elements

In [114… print(np.mean(arr ,axis=0))


print("--------------------------")
(38+
6+
8+
19+
15+
31)/6
# no of rows = 6

[19.5 27.5 13.33333333 22.16666667 24.33333333 25.5 ]


--------------------------
19.5
Out[114]:

In [115… print(np.mean(arr ,axis=1))


print("--------------------------")
(38 + 44 + 13 + 9 + 10 + 12)/6
# no of columns = 6

[21. 9.16666667 24.33333333 25.66666667 26.66666667 25.5 ]


--------------------------
21.0
Out[115]:

np.median()
It return the median of an array

Syntax:

localhost:8888/doc/tree/OneDrive/Desktop/PYTHON'S FILES/NUMPY.ipynb 41/80


1/13/24, 10:51 AM NUMPY

np.median(arr, axis = 0,1)

In [116… arr

array([[38, 44, 13, 9, 10, 12],


Out[116]:
[ 6, 16, 1, 17, 2, 13],
[ 8, 46, 7, 26, 21, 38],
[19, 21, 12, 43, 29, 30],
[15, 5, 24, 24, 42, 50],
[31, 33, 23, 14, 42, 10]])

In [117… np.median(arr , axis = 0)

array([17. , 27. , 12.5, 20.5, 25. , 21.5])


Out[117]:

In [126… print("sorted of rows axis 6 + 8 + 15 + 19 + 31 + 38 : ", (15 + 19)/2)


print("15 AND 19 are the sorted middle numbers of rows axis ")

sorted of rows axis 6 + 8 + 15 + 19 + 31 + 38 : 17.0


15 AND 19 are the sorted middle numbers of rows axis

In [127… np.median(arr , axis = 1)

array([12.5, 9.5, 23.5, 25. , 24. , 27. ])


Out[127]:

In [128… print("sorted of columns axis 9 + 10 + 12 + 13 + 38 + 44 : ", (12 + 13)/2)


print("12 AND 13 are the sorted middle numbers of columns axis ")

sorted of columns axis 9 + 10 + 12 + 13 + 38 + 44 : 12.5


12 AND 13 are the sorted middle numbers of columns axis

Formula for median is : sorted middle indexes of (rows/columns)


of an array /2

np.var()
It return the variance of the array

Syntax:

np.var(arr, axis = 0,1)

In [3]: import numpy as np

np.random.seed(1)
x = np.random.randint(1,51,16).reshape(4,4)
x

array([[38, 44, 13, 9],


Out[3]:
[10, 12, 6, 16],
[ 1, 17, 2, 13],
[ 8, 46, 7, 26]])

In [4]: x.var()

localhost:8888/doc/tree/OneDrive/Desktop/PYTHON'S FILES/NUMPY.ipynb 42/80


1/13/24, 10:51 AM NUMPY
190.3125
Out[4]:

In [5]: np.var(x , axis=0)

array([199.1875, 236.1875, 15.5 , 39.5 ])


Out[5]:

In [8]: np.mean(x , axis=0)

array([14.25, 29.75, 7. , 16. ])


Out[8]:

In [7]: np.mean(x)

16.75
Out[7]:

In [6]: np.var(x , axis=1)

array([231.5 , 13. , 47.6875, 253.1875])


Out[6]:

In [10]: np.mean(x , axis=1)

array([26. , 11. , 8.25, 21.75])


Out[10]:

Formula : Number of axis(0 (rows),1(Columns)) - Mean of axis(0(rows)


,1(columns))**2 + That whole axis(0,1) / number of layers or array

In [9]: ((38-14.25)**2 + (10-14.25)**2 +(1-14.25)**2 +(8-14.25)**2)/4

199.1875
Out[9]:

In [11]: ((38-26)**2 + (44-26)**2 +(13-26)**2 +(9-26)**2)/4

231.5
Out[11]:

np.std()
It returns the standard deviation of an array

Syntax:

np.std(arr, axis = 0,1)

In [8]: np.random.seed(1)
axisss = np.random.randint(1,30,25).reshape(5,5)
axisss

array([[ 6, 12, 13, 9, 10],


Out[8]:
[12, 6, 16, 1, 17],
[ 2, 13, 8, 14, 29],
[ 7, 26, 19, 21, 6],
[19, 21, 12, 29, 11]])

In [10]: v = np.mean(axisss , axis=0)


c = np.var(axisss , axis=0)

localhost:8888/doc/tree/OneDrive/Desktop/PYTHON'S FILES/NUMPY.ipynb 43/80


1/13/24, 10:51 AM NUMPY

print(v)
print(c)

[ 9.2 15.6 13.6 14.8 14.6]


[34.16 49.84 13.84 92.96 64.24]

Solving of Variances

In [16]: ((6-9.2)**2 + (12-9.2)**2 + (2-9.2)**2 + (7-9.2)**2 + (19-9.2)**2)/5

34.160000000000004
Out[16]:

In [11]: np.std(axisss , axis= 0)

array([5.84465568, 7.05974504, 3.72021505, 9.64157663, 8.01498596])


Out[11]:

Formula : sqrt(variance of axis (0,1))

In [12]: import math

In [14]: math.sqrt(34.16)

5.844655678480983
Out[14]:

Note : For finding Standard Deviation : 1. We have to first find the


mean(np.mean()) of the array of axis(0,1)

2. After that from mean we have to find the variance(np.var()) of the array of
axis(0,1)

3. Afterwards from that We have to do square of variances of that particular


axis(0,1) for standard deviation(np.std()) we have to find.

In [5]: np.random.seed(1)
garryy = np.random.randint(1,22,25).reshape(5,5)
garryy

array([[ 6, 12, 13, 9, 10],


Out[5]:
[12, 6, 16, 1, 17],
[ 2, 13, 8, 14, 7],
[19, 21, 6, 19, 21],
[12, 11, 15, 19, 5]])

In [18]: print(np.mean(garryy))
print(np.var(garryy))
print(np.std(garryy))

11.76
31.862399999999997
5.644678910265844

In [19]: math.sqrt(31.862399999999997)

5.644678910265844
Out[19]:

localhost:8888/doc/tree/OneDrive/Desktop/PYTHON'S FILES/NUMPY.ipynb 44/80


1/13/24, 10:51 AM NUMPY

np.min()
It return the minimum value of the arary

Syntax:

np.min(arr, axis = 0,1)

In [20]: garryy

array([[ 6, 12, 13, 9, 10],


Out[20]:
[12, 6, 16, 1, 17],
[ 2, 13, 8, 14, 7],
[19, 21, 6, 19, 21],
[12, 11, 15, 19, 5]])

In [21]: np.min(garryy)

1
Out[21]:

As you can see in below it shows that by finding np.min() we find minimum value and it
checks the all the axis of 0 (rows) of the array and give each value from each row specifically
minimum value.

In [22]: np.min(garryy , axis=0)

array([2, 6, 6, 1, 5])
Out[22]:

In [23]: np.min(garryy , axis=1)

array([6, 1, 2, 6, 5])
Out[23]:

np.max()
It return the maximum value of the arary

Syntax:

np.max(arr, axis = 0,1)

In [24]: garryy

array([[ 6, 12, 13, 9, 10],


Out[24]:
[12, 6, 16, 1, 17],
[ 2, 13, 8, 14, 7],
[19, 21, 6, 19, 21],
[12, 11, 15, 19, 5]])

In [25]: np.max(garryy)

21
Out[25]:

As you can see in below it shows that by finding np.max() we find maximum value and it
checks the all the axis of 0 (rows) of the array and give each value from each row specifically

localhost:8888/doc/tree/OneDrive/Desktop/PYTHON'S FILES/NUMPY.ipynb 45/80


1/13/24, 10:51 AM NUMPY
maximum value.

In [26]: np.max(garryy , axis= 0)

array([19, 21, 16, 19, 21])


Out[26]:

In [27]: np.max(garryy , axis=1)

array([13, 17, 14, 21, 19])


Out[27]:

np.percentile()
It return the specified percentile value of the array

In [6]: garryy

array([[ 6, 12, 13, 9, 10],


Out[6]:
[12, 6, 16, 1, 17],
[ 2, 13, 8, 14, 7],
[19, 21, 6, 19, 21],
[12, 11, 15, 19, 5]])

In [32]: np.percentile(garryy , 10)

5.4
Out[32]:

In [8]: flat_array = garryy.flatten()


sorted_array = np.sort(flat_array)
Index = (10 / 100) * (25 - 1)
percentile_index = (10 / 100) * (len(sorted_array) - 1)
interpolated_value = np.interp(percentile_index, np.arange(len(sorted_array)), sorted_
print(interpolated_value)

5.4

In [36]: len(garryy)

5
Out[36]:

In [33]: np.percentile(garryy , 7)

4.040000000000001
Out[33]:

In [53]: a = garryy.flatten()
a

array([ 6, 12, 13, 9, 10, 12, 6, 16, 1, 17, 2, 13, 8, 14, 7, 19, 21,
Out[53]:
6, 19, 21, 12, 11, 15, 19, 5])

In [54]: np.sort(a)

array([ 1, 2, 5, 6, 6, 6, 7, 8, 9, 10, 11, 12, 12, 12, 13, 13, 14,


Out[54]:
15, 16, 17, 19, 19, 19, 21, 21])

astype() :

localhost:8888/doc/tree/OneDrive/Desktop/PYTHON'S FILES/NUMPY.ipynb 46/80


1/13/24, 10:51 AM NUMPY

It typecast one data type to another.

In [20]: arr1 = np.array([2,3.8 , 8 ,89 , 77.3 , 66.5 ,33.2 , 12.3])


arr1

array([ 2. , 3.8, 8. , 89. , 77.3, 66.5, 33.2, 12.3])


Out[20]:

In [21]: arr1.astype(int)

array([ 2, 3, 8, 89, 77, 66, 33, 12])


Out[21]:

In [22]: arr1.astype(complex)

array([ 2. +0.j, 3.8+0.j, 8. +0.j, 89. +0.j, 77.3+0.j, 66.5+0.j,


Out[22]:
33.2+0.j, 12.3+0.j])

In [23]: arr1.astype(str)

array(['2.0', '3.8', '8.0', '89.0', '77.3', '66.5', '33.2', '12.3'],


Out[23]:
dtype='<U32')

In [25]: arr1.astype(float)

array([ 2. , 3.8, 8. , 89. , 77.3, 66.5, 33.2, 12.3])


Out[25]:

In [26]: arr1.astype(bool)

array([ True, True, True, True, True, True, True, True])


Out[26]:

In [27]: arr1.astype(list)

array([2.0, 3.8, 8.0, 89.0, 77.3, 66.5, 33.2, 12.3], dtype=object)


Out[27]:

In [28]: arr1.astype(set)

array([2.0, 3.8, 8.0, 89.0, 77.3, 66.5, 33.2, 12.3], dtype=object)


Out[28]:

Null Values in NUMPY


In Python normal null value represent by the NONE
But in Numpy library We can represent the null value by np.nan
by default np.nan is 1 ----> which means that np.nan is true by default.

NAN stands for Not A Number

By default np.nan gives value in float datatype.

In [29]: a = None
print(a , type(a))

None <class 'NoneType'>

In [30]: arr1 = np.array([np.nan])


print(arr1 , type(arr1))

localhost:8888/doc/tree/OneDrive/Desktop/PYTHON'S FILES/NUMPY.ipynb 47/80


1/13/24, 10:51 AM NUMPY
[nan] <class 'numpy.ndarray'>

In [31]: arr1.dtype

dtype('float64')
Out[31]:

In [32]: arr2 = np.array([12, 34, np.nan , 32 , np.nan , 45 , 67, np.nan , 99 ]).reshape(3,3)


arr2

array([[12., 34., nan],


Out[32]:
[32., nan, 45.],
[67., nan, 99.]])

As you can see now by default array is in float data type. because of np.nan

In [33]: arr2.dtype

dtype('float64')
Out[33]:

Operations on Null Values


Count the number of null values in array.
Accessing the null values from an array.
Count the non null values in the array.
Accessing the non null values from an array.
Replacing the null values in the array.

np.isnan()
It checks for nan values and returns a boolean array, where True means the null value is
present and False means the non-null values is present

In [34]: arr2

array([[12., 34., nan],


Out[34]:
[32., nan, 45.],
[67., nan, 99.]])

In [35]: np.isnan(arr2)

array([[False, False, True],


Out[35]:
[False, True, False],
[False, True, False]])

Count the null values and Non null values inside the array
Syntax :

np.isnan().sum() ----- For Null values

(~ np.isnan()).sum() ----- For non Null Values

localhost:8888/doc/tree/OneDrive/Desktop/PYTHON'S FILES/NUMPY.ipynb 48/80


1/13/24, 10:51 AM NUMPY

In [37]: arr2

array([[12., 34., nan],


Out[37]:
[32., nan, 45.],
[67., nan, 99.]])

In [38]: np.isnan(arr2)

array([[False, False, True],


Out[38]:
[False, True, False],
[False, True, False]])

In [36]: np.isnan(arr2).sum()

3
Out[36]:

In [65]: (~np.isnan(arr2)).sum()

6
Out[65]:

In [68]: (np.isnan(arr2) == False ).sum()

6
Out[68]:

In [70]: len(arr2[np.isnan(arr2) == False])

6
Out[70]:

In [66]: arr2[np.isnan(arr2) == True]

array([nan, nan, nan])


Out[66]:

In [67]: arr2[(~np.isnan(arr2) == True)]

array([12., 34., 32., 45., 67., 99.])


Out[67]:

Accessing the null values from an array


Syntax :

np.where(condition)

np.where(condition)

- It helps to fetch the values based on some


conditions

It returns the index of the element where the


condition is True

localhost:8888/doc/tree/OneDrive/Desktop/PYTHON'S FILES/NUMPY.ipynb 49/80


1/13/24, 10:51 AM NUMPY

To fetch the element we pass np.where () as the index to the array object

In [39]: arr2

array([[12., 34., nan],


Out[39]:
[32., nan, 45.],
[67., nan, 99.]])

In [40]: np.where(np.isnan(arr2))

(array([0, 1, 2], dtype=int64), array([2, 1, 1], dtype=int64))


Out[40]:

As you can see in above code that it is returning two arrays first tarray tells us about the
layers or lists in the array by indexing numbers and the another array states the position
where nan values are there.

As you can see at 0th list --- at 2nd position there is an nan value.

In [41]: np.random.seed(1)
arr3 = np.random.randint(1,51,36).reshape(4,9)
arr3

array([[38, 44, 13, 9, 10, 12, 6, 16, 1],


Out[41]:
[17, 2, 13, 8, 46, 7, 26, 21, 38],
[19, 21, 12, 43, 29, 30, 15, 5, 24],
[24, 42, 50, 31, 33, 23, 14, 42, 10]])

In [43]: np.where(arr3 > 35)

(array([0, 0, 1, 1, 2, 3, 3, 3], dtype=int64),


Out[43]:
array([0, 1, 4, 8, 3, 1, 2, 7], dtype=int64))

In [44]: np.random.seed(45)
arr = np.random.randint(10,100,12).reshape(3,2,2)
arr

array([[[85, 40],
Out[44]:
[13, 42]],

[[71, 95],
[45, 78]],

[[25, 75],
[24, 63]]])

In [46]: np.where(arr > 40)

(array([0, 0, 1, 1, 1, 1, 2, 2], dtype=int64),


Out[46]:
array([0, 1, 0, 0, 1, 1, 0, 1], dtype=int64),
array([0, 1, 0, 1, 0, 1, 1, 1], dtype=int64))

In [45]: arr > 50

localhost:8888/doc/tree/OneDrive/Desktop/PYTHON'S FILES/NUMPY.ipynb 50/80


1/13/24, 10:51 AM NUMPY
array([[[ True, False],
Out[45]:
[False, False]],

[[ True, True],
[False, True]],

[[False, True],
[False, True]]])

In [32]: arr7 = np.array([12, np.nan , np.nan , 55 , np.nan , 99 , np.nan , 76 , np.nan , 45 ,


arr7

array([[ 12., nan, nan, 55.],


Out[32]:
[ nan, 99., nan, 76.],
[ nan, 45., 345., nan]])

In [33]: np.where(np.isnan(arr7))

(array([0, 0, 1, 1, 2, 2], dtype=int64),


Out[33]:
array([1, 2, 0, 2, 0, 3], dtype=int64))

In [34]: arr7[np.where(np.isnan(arr7))]

array([nan, nan, nan, nan, nan, nan])


Out[34]:

In [35]: arr7[np.isnan(arr7) == True]

array([nan, nan, nan, nan, nan, nan])


Out[35]:

Accessing the non Null Values


In [56]: arr

array([[[85, 40],
Out[56]:
[13, 42]],

[[71, 95],
[45, 78]],

[[25, 75],
[24, 63]]])

In [71]: arr[np.where(arr > 20)]

array([85, 40, 42, 71, 95, 45, 78, 25, 75, 24, 63])
Out[71]:

In [62]: arr[(arr> 20) == True]

array([85, 40, 42, 71, 95, 45, 78, 25, 75, 24, 63])
Out[62]:

np.where --- Case 2


Syntax : np.where(condition, x, y)
If the condition is True, then x is the result, otherwise y is the result

localhost:8888/doc/tree/OneDrive/Desktop/PYTHON'S FILES/NUMPY.ipynb 51/80


1/13/24, 10:51 AM NUMPY

In [74]: np.random.seed(10)
arr2 = np.random.randint(1,51,36).reshape(6,6)
arr2

array([[10, 37, 16, 1, 50, 29],


Out[74]:
[26, 30, 49, 30, 50, 9],
[10, 1, 43, 41, 37, 17],
[37, 48, 12, 25, 44, 34],
[ 9, 37, 15, 50, 14, 6],
[14, 26, 14, 29, 23, 31]])

In [75]: np.where(arr2%2==0 , "Even" , "Odd")

array([['Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd'],


Out[75]:
['Even', 'Even', 'Odd', 'Even', 'Even', 'Odd'],
['Even', 'Odd', 'Odd', 'Odd', 'Odd', 'Odd'],
['Odd', 'Even', 'Even', 'Odd', 'Even', 'Even'],
['Odd', 'Odd', 'Odd', 'Even', 'Even', 'Even'],
['Even', 'Even', 'Even', 'Odd', 'Odd', 'Odd']], dtype='<U4')

In [77]: np.where(arr2 < 40 , True , False)

array([[ True, True, True, True, False, True],


Out[77]:
[ True, True, False, True, False, True],
[ True, True, False, False, True, True],
[ True, False, True, True, False, True],
[ True, True, True, False, True, True],
[ True, True, True, True, True, True]])

np.where -- Case 3
Syntax : - np.where(condition, x, arr)
If the condition is True, then x is the result, otherwise the value remains the same

In [78]: arr2

array([[10, 37, 16, 1, 50, 29],


Out[78]:
[26, 30, 49, 30, 50, 9],
[10, 1, 43, 41, 37, 17],
[37, 48, 12, 25, 44, 34],
[ 9, 37, 15, 50, 14, 6],
[14, 26, 14, 29, 23, 31]])

In [79]: np.where(arr2%2 , "even" , arr2)

array([['10', 'even', '16', 'even', '50', 'even'],


Out[79]:
['26', '30', 'even', '30', '50', 'even'],
['10', 'even', 'even', 'even', 'even', 'even'],
['even', '48', '12', 'even', '44', '34'],
['even', 'even', 'even', '50', '14', '6'],
['14', '26', '14', 'even', 'even', 'even']], dtype='<U11')

In [80]: np.where(arr2 < 40 , 1 , arr2)

localhost:8888/doc/tree/OneDrive/Desktop/PYTHON'S FILES/NUMPY.ipynb 52/80


1/13/24, 10:51 AM NUMPY
array([[ 1, 1, 1, 1, 50, 1],
Out[80]:
[ 1, 1, 49, 1, 50, 1],
[ 1, 1, 43, 41, 1, 1],
[ 1, 48, 1, 1, 44, 1],
[ 1, 1, 1, 50, 1, 1],
[ 1, 1, 1, 1, 1, 1]])

Replace the Null Values in an array


In [36]: arr7

array([[ 12., nan, nan, 55.],


Out[36]:
[ nan, 99., nan, 76.],
[ nan, 45., 345., nan]])

In [37]: arr7[np.isnan(arr7)] = 1

In [41]: arr7

array([[ 12., 1., 1., 55.],


Out[41]:
[ 1., 99., 1., 76.],
[ 1., 45., 345., 1.]])

In [40]: arr7.astype(int)

array([[ 12, 1, 1, 55],


Out[40]:
[ 1, 99, 1, 76],
[ 1, 45, 345, 1]])

Replacing all the Null values with means , medians

Both are the ways : arr[np.isnan(arr) == False].mean()

arr[np.isnan(arr)] = arr(~np.isnan(arr)).mean()

By mean
In [42]: arr = np.array([10,20,30, np.nan, 50, np.nan, 45, 60, np.nan, np.nan, 78, 62]).reshape
arr

array([[10., 20., 30., nan],


Out[42]:
[50., nan, 45., 60.],
[nan, nan, 78., 62.]])

In [43]: arr.mean()

nan
Out[43]:

In [44]: m = arr[np.isnan(arr) == False].mean()


m

44.375
Out[44]:

In [45]: arr[np.isnan(arr)] = arr[np.isnan(arr) == False].mean()

localhost:8888/doc/tree/OneDrive/Desktop/PYTHON'S FILES/NUMPY.ipynb 53/80


1/13/24, 10:51 AM NUMPY

In [46]: arr

array([[10. , 20. , 30. , 44.375],


Out[46]:
[50. , 44.375, 45. , 60. ],
[44.375, 44.375, 78. , 62. ]])

In [64]: a = np.array([ 1 ,2 , 3 , np.nan , 5 ,6 , np.nan , np.nan , 76]).reshape(3,3)


a

array([[ 1., 2., 3.],


Out[64]:
[nan, 5., 6.],
[nan, nan, 76.]])

In [48]: a.mean()

nan
Out[48]:

In [49]: y = a[np.isnan(a) == False].mean()


y

15.5
Out[49]:

In [62]: a[np.isnan(a)] = y

In [63]: a

array([[ 1. , 2. , 3. ],
Out[63]:
[15.5, 5. , 6. ],
[15.5, 15.5, 76. ]])

By Median
In [65]: a

array([[ 1., 2., 3.],


Out[65]:
[nan, 5., 6.],
[nan, nan, 76.]])

In [67]: np.median(a)

nan
Out[67]:

In [71]: m = a[np.isnan(a) == False]

In [72]: np.median(m)

4.0
Out[72]:

In [73]: a[np.isnan(a)] = np.median(m)

In [74]: a

array([[ 1., 2., 3.],


Out[74]:
[ 4., 5., 6.],
[ 4., 4., 76.]])

localhost:8888/doc/tree/OneDrive/Desktop/PYTHON'S FILES/NUMPY.ipynb 54/80


1/13/24, 10:51 AM NUMPY

In [76]: z = np.array([ 12 , np.nan , 24 , np.nan , 36 , np.nan , 48 , np.nan , 60 , np.nan , 7


z

array([[12., nan, 24., nan],


Out[76]:
[36., nan, 48., nan],
[60., nan, 72., 84.]])

In [77]: np.mean(z)

nan
Out[77]:

In [79]: meannn = z[np.isnan(z) == False].mean()


meannn

48.0
Out[79]:

In [81]: z[np.isnan(z)] = meannn

In [82]: z

array([[12., 48., 24., 48.],


Out[82]:
[36., 48., 48., 48.],
[60., 48., 72., 84.]])

In [83]: b = np.array([23 , 32 , np.nan , np.nan , 45 , 54 , np.nan , 67 , np.nan]).reshape(3,3


b

array([[23., 32., nan],


Out[83]:
[nan, 45., 54.],
[nan, 67., nan]])

In [84]: np.median(b)

nan
Out[84]:

In [86]: v = b[np.isnan(b) == False]

In [90]: mediannn = np.median(v)


mediannn

45.0
Out[90]:

In [91]: b[np.isnan(b)] = mediannn

In [92]: b

array([[23., 32., 45.],


Out[92]:
[45., 45., 54.],
[45., 67., 45.]])

In [93]: b.astype(int)

array([[23, 32, 45],


Out[93]:
[45, 45, 54],
[45, 67, 45]])

Replacing Null values By mean


localhost:8888/doc/tree/OneDrive/Desktop/PYTHON'S FILES/NUMPY.ipynb 55/80
1/13/24, 10:51 AM NUMPY

In [94]: arr1 = np.array([np.nan , 32 , 23 , np.nan , np.nan , np.nan , 76 , 87 , np.nan]).resh


arr1

array([[nan, 32., 23.],


Out[94]:
[nan, nan, nan],
[76., 87., nan]])

In [96]: print(arr.mean())
print("----------------------------------------------------------")
w = arr1[np.isnan(arr1) == False].mean()
print(w)
print("----------------------------------------------------------")
arr1[np.isnan(arr1)] = w
print(arr1)

44.375
----------------------------------------------------------
54.5
----------------------------------------------------------
[[54.5 32. 23. ]
[54.5 54.5 54.5]
[76. 87. 54.5]]

Replacing Null values By Median


In [97]: arr9 = np.array([np.nan , 101 , 223 , np.nan , np.nan , np.nan , 676 , 787 , np.nan]).
arr9

array([[ nan, 101., 223.],


Out[97]:
[ nan, nan, nan],
[676., 787., nan]])

In [98]: print(np.median(arr9))
print("-------------------------------------------------------")
qqq = arr9[np.isnan(arr9) == False]
x = np.median(qqq)
print(x)
print("-------------------------------------------------------")
arr9[np.isnan(arr9)] = x
print(arr9)

nan
-------------------------------------------------------
449.5
-------------------------------------------------------
[[449.5 101. 223. ]
[449.5 449.5 449.5]
[676. 787. 449.5]]

In [122… arr9 = np.array([np.nan , 101 , 223 , np.nan , np.nan , np.nan , 676 , 787 , np.nan]).
arr9

array([[ nan, 101., 223.],


Out[122]:
[ nan, nan, nan],
[676., 787., nan]])

As you can see in below code , I've replaced non null values with 22 and null values with
zero(0)

localhost:8888/doc/tree/OneDrive/Desktop/PYTHON'S FILES/NUMPY.ipynb 56/80


1/13/24, 10:51 AM NUMPY

In [123… arr9[np.isnan(arr9) == False]= 22


arr9[np.isnan(arr9) == True] = 0

In [124… arr9

array([[ 0., 22., 22.],


Out[124]:
[ 0., 0., 0.],
[22., 22., 0.]])

In [126… arr9.astype(int)

array([[ 0, 22, 22],


Out[126]:
[ 0, 0, 0],
[22, 22, 0]])

np.argwhere()
It returns an array object that contains the indexes of all the non zero element from the
array

Syntax:

np.argwhere(arr)

In [127… arr9

array([[ 0., 22., 22.],


Out[127]:
[ 0., 0., 0.],
[22., 22., 0.]])

In [128… np.argwhere(arr9)

array([[0, 1],
Out[128]:
[0, 2],
[2, 0],
[2, 1]], dtype=int64)

In [129… arr1

array([[54.5, 32. , 23. ],


Out[129]:
[54.5, 54.5, 54.5],
[76. , 87. , 54.5]])

In [130… np.argwhere(arr1)

array([[0, 0],
Out[130]:
[0, 1],
[0, 2],
[1, 0],
[1, 1],
[1, 2],
[2, 0],
[2, 1],
[2, 2]], dtype=int64)

As you can see that in this array there is no zero elements so it giving all the indexes

localhost:8888/doc/tree/OneDrive/Desktop/PYTHON'S FILES/NUMPY.ipynb 57/80


1/13/24, 10:51 AM NUMPY

In [145… argg = np.array([ 1, 2, 3, 4, 5, 0, 0, 78, 9, 0, 7, 89, 0, 222, 0])


print(argg)
print("-------------------------------------------------------------------")
print("Non - Zero elements Indexes : " , np.argwhere(argg))
print("-------------------------------------------------------------------")
print("Zero Elements Indexes : ", np.argwhere(argg == 0))

[ 1 2 3 4 5 0 0 78 9 0 7 89 0 222 0]
-------------------------------------------------------------------
Non - Zero elements Indexes : [[ 0]
[ 1]
[ 2]
[ 3]
[ 4]
[ 7]
[ 8]
[10]
[11]
[13]]
-------------------------------------------------------------------
Zero Elements Indexes : [[ 5]
[ 6]
[ 9]
[12]
[14]]

As you can see we can see the indexes of zero elements also by giving conditions in it.

np.argmax()
It returns the index of the maximum number
In case of multiple maximum number, it will return the index of the first maximum number
It treats the n-d array as 1-D array

In [147… arr1

array([[54.5, 32. , 23. ],


Out[147]:
[54.5, 54.5, 54.5],
[76. , 87. , 54.5]])

In [148… np.argmax(arr1)

7
Out[148]:

As you can see , it is giving index 7th of the arr1 which is 87 . as you can see it treats the array
ino 1D array.

np.argmin()
It returns the index of the minimum number
In case of multiple minimum number, it will return the index of the first minimum number
It treats the n-d array as 1-D array

In [149… arr1

localhost:8888/doc/tree/OneDrive/Desktop/PYTHON'S FILES/NUMPY.ipynb 58/80


1/13/24, 10:51 AM NUMPY
array([[54.5, 32. , 23. ],
Out[149]:
[54.5, 54.5, 54.5],
[76. , 87. , 54.5]])

In [150… np.argmin(arr1)

2
Out[150]:

As you can see , it is giving index 2nd of the arr1 which is 23 . as you can see it treats the
array ino 1D array.

Capping The Value


In [159… np.random.seed(10)
arrg = np.random.randint(1,51,36).reshape(6,6)
arrg

array([[10, 37, 16, 1, 50, 29],


Out[159]:
[26, 30, 49, 30, 50, 9],
[10, 1, 43, 41, 37, 17],
[37, 48, 12, 25, 44, 34],
[ 9, 37, 15, 50, 14, 6],
[14, 26, 14, 29, 23, 31]])

cap the value of the above the above array between the range 40 -70

any value less than 40-->40 || any value greater than 70 --->70

In [160… np.where(arrg > 70 , 70 , np.where(arrg < 40 , 40 , arrg))

array([[40, 40, 40, 40, 50, 40],


Out[160]:
[40, 40, 49, 40, 50, 40],
[40, 40, 43, 41, 40, 40],
[40, 48, 40, 40, 44, 40],
[40, 40, 40, 50, 40, 40],
[40, 40, 40, 40, 40, 40]])

In [178… np.random.seed(1)
arrg2 = np.random.randint(100,510,36).reshape(6,6)
arrg2

array([[137, 335, 496, 172, 355, 493],


Out[178]:
[303, 233, 435, 244, 229, 171],
[337, 490, 381, 278, 376, 354],
[457, 502, 495, 352, 256, 498],
[150, 168, 315, 341, 452, 186],
[241, 493, 107, 419, 417, 122]])

cap the value of the above the above array between the range 250

any value less than 250-->"Less Than 250" || any value greater than 250 --->"Greater than
250"

In [179… strr_ = np.where(arrg2 > 250 , "Greater than 250", np.where(arrg < 250 , "Less than 25
strr_.astype(str)

localhost:8888/doc/tree/OneDrive/Desktop/PYTHON'S FILES/NUMPY.ipynb 59/80


1/13/24, 10:51 AM NUMPY
array([['Less than 250', 'Greater than 250', 'Greater than 250',
Out[179]:
'Less than 250', 'Greater than 250', 'Greater than 250'],
['Greater than 250', 'Less than 250', 'Greater than 250',
'Less than 250', 'Less than 250', 'Less than 250'],
['Greater than 250', 'Greater than 250', 'Greater than 250',
'Greater than 250', 'Greater than 250', 'Greater than 250'],
['Greater than 250', 'Greater than 250', 'Greater than 250',
'Greater than 250', 'Greater than 250', 'Greater than 250'],
['Less than 250', 'Less than 250', 'Greater than 250',
'Greater than 250', 'Greater than 250', 'Less than 250'],
['Less than 250', 'Greater than 250', 'Less than 250',
'Greater than 250', 'Greater than 250', 'Less than 250']],
dtype='<U16')

np.clip()
It is used to clipping the value between lower limit to upper limit.

Syntax

np.clip(arr , lower_limit , upper_limit)

In [206… arrg

array([[10, 37, 16, 1, 50, 29],


Out[206]:
[26, 30, 49, 30, 50, 9],
[10, 1, 43, 41, 37, 17],
[37, 48, 12, 25, 44, 34],
[ 9, 37, 15, 50, 14, 6],
[14, 26, 14, 29, 23, 31]])

In [208… np.clip(arrg , 20 , 30)

array([[20, 30, 20, 20, 30, 29],


Out[208]:
[26, 30, 30, 30, 30, 20],
[20, 20, 30, 30, 30, 20],
[30, 30, 20, 25, 30, 30],
[20, 30, 20, 30, 20, 20],
[20, 26, 20, 29, 23, 30]])

In [209… arrg2

array([[137, 335, 496, 172, 355, 493],


Out[209]:
[303, 233, 435, 244, 229, 171],
[337, 490, 381, 278, 376, 354],
[457, 502, 495, 352, 256, 498],
[150, 168, 315, 341, 452, 186],
[241, 493, 107, 419, 417, 122]])

In [210… np.clip(arrg2 , 200 , 350)

array([[200, 335, 350, 200, 350, 350],


Out[210]:
[303, 233, 350, 244, 229, 200],
[337, 350, 350, 278, 350, 350],
[350, 350, 350, 350, 256, 350],
[200, 200, 315, 341, 350, 200],
[241, 350, 200, 350, 350, 200]])

localhost:8888/doc/tree/OneDrive/Desktop/PYTHON'S FILES/NUMPY.ipynb 60/80


1/13/24, 10:51 AM NUMPY

In [5]: np.random.seed(7)
arr = np.random.randint(1,51,36).reshape(6,6)
arr

array([[48, 5, 26, 4, 20, 24],


Out[5]:
[40, 29, 15, 24, 9, 26],
[47, 43, 27, 9, 40, 39],
[ 5, 49, 8, 45, 1, 12],
[ 7, 20, 45, 6, 25, 49],
[ 1, 35, 10, 15, 39, 5]])

In [6]: np.diag(arr)

array([48, 29, 27, 45, 25, 5])


Out[6]:

In [7]: np.diag(np.diag(arr))

array([[48, 0, 0, 0, 0, 0],
Out[7]:
[ 0, 29, 0, 0, 0, 0],
[ 0, 0, 27, 0, 0, 0],
[ 0, 0, 0, 45, 0, 0],
[ 0, 0, 0, 0, 25, 0],
[ 0, 0, 0, 0, 0, 5]])

In [8]: arr

array([[48, 5, 26, 4, 20, 24],


Out[8]:
[40, 29, 15, 24, 9, 26],
[47, 43, 27, 9, 40, 39],
[ 5, 49, 8, 45, 1, 12],
[ 7, 20, 45, 6, 25, 49],
[ 1, 35, 10, 15, 39, 5]])

In [10]: print(np.mean(arr))
print(np.var(arr))
print(np.std(arr))

23.666666666666668
253.16666666666666
15.911211979816832

In [11]: import math


math.sqrt(253.16666666666666)

15.911211979816832
Out[11]:

In [12]: np.median(arr)

24.0
Out[12]:

In [13]: arr3 = np.array([12, np.nan , 31 , np.nan , np.nan , np.nan , 34 ,35 , 89]).reshape(3,


arr3

array([[12., nan, 31.],


Out[13]:
[nan, nan, nan],
[34., 35., 89.]])

In [15]: arr3[np.isnan(arr3) == False]

localhost:8888/doc/tree/OneDrive/Desktop/PYTHON'S FILES/NUMPY.ipynb 61/80


1/13/24, 10:51 AM NUMPY
array([12., 31., 34., 35., 89.])
Out[15]:

In [17]: meann = arr3[np.isnan(arr3) == False].mean()


meann

40.2
Out[17]:

In [21]: arr3[np.isnan(arr3)] = meann


print(arr3)

[[12. 40.2 31. ]


[40.2 40.2 40.2]
[34. 35. 89. ]]

In [20]: arr3.astype(int)

array([[12, 40, 31],


Out[20]:
[40, 40, 40],
[34, 35, 89]])

In [22]: arr

array([[48, 5, 26, 4, 20, 24],


Out[22]:
[40, 29, 15, 24, 9, 26],
[47, 43, 27, 9, 40, 39],
[ 5, 49, 8, 45, 1, 12],
[ 7, 20, 45, 6, 25, 49],
[ 1, 35, 10, 15, 39, 5]])

In [23]: arr[1,(0,1,2,3,4,5)] = 22,21,19,15,51,21


arr

array([[48, 5, 26, 4, 20, 24],


Out[23]:
[22, 21, 19, 15, 51, 21],
[47, 43, 27, 9, 40, 39],
[ 5, 49, 8, 45, 1, 12],
[ 7, 20, 45, 6, 25, 49],
[ 1, 35, 10, 15, 39, 5]])

In [28]: arr[:: , :1:]

array([[48],
Out[28]:
[22],
[47],
[ 5],
[ 7],
[ 1]])

Condition Statements on Array


It returns boolean values of array. Syntax

arr_name[condition]

In [3]: np.random.seed(12)
arr1 = np.random.randint(22,87,36).reshape(6,6)
arr1

localhost:8888/doc/tree/OneDrive/Desktop/PYTHON'S FILES/NUMPY.ipynb 62/80


1/13/24, 10:51 AM NUMPY
array([[49, 28, 24, 25, 70, 44],
Out[3]:
[71, 74, 27, 35, 56, 22],
[35, 57, 84, 57, 55, 52],
[85, 40, 72, 28, 67, 52],
[54, 49, 81, 81, 47, 78],
[26, 66, 59, 75, 75, 69]])

As you can see in below code that it is giving bool values of arrays because we directly put
arr1>25 if we put the same condition inside arr_name then it'll only show the greater
elements of arr1 by 25 you can see in below codes.

In [4]: arr1>25

array([[ True, True, False, False, True, True],


Out[4]:
[ True, True, True, True, True, False],
[ True, True, True, True, True, True],
[ True, True, True, True, True, True],
[ True, True, True, True, True, True],
[ True, True, True, True, True, True]])

In [5]: arr1[arr1>25]

array([49, 28, 70, 44, 71, 74, 27, 35, 56, 35, 57, 84, 57, 55, 52, 85, 40,
Out[5]:
72, 28, 67, 52, 54, 49, 81, 81, 47, 78, 26, 66, 59, 75, 75, 69])

In [7]: arr1[arr1<36]

array([28, 24, 25, 27, 35, 22, 35, 28, 26])


Out[7]:

Filtering elements by giving conditions


In [8]: arr1

array([[49, 28, 24, 25, 70, 44],


Out[8]:
[71, 74, 27, 35, 56, 22],
[35, 57, 84, 57, 55, 52],
[85, 40, 72, 28, 67, 52],
[54, 49, 81, 81, 47, 78],
[26, 66, 59, 75, 75, 69]])

In [11]: arr1[(arr1 % 3 ==0) & (arr1 % 2 == 0) ]

array([24, 84, 72, 54, 78, 66])


Out[11]:

In [12]: import seaborn as sns

In [14]: df = sns.load_dataset("titanic")
df.head()

localhost:8888/doc/tree/OneDrive/Desktop/PYTHON'S FILES/NUMPY.ipynb 63/80


1/13/24, 10:51 AM NUMPY

Out[14]: survived pclass sex age sibsp parch fare embarked class who adult_male deck

0 0 3 male 22.0 1 0 7.2500 S Third man True NaN

1 1 1 female 38.0 1 0 71.2833 C First woman False C

2 1 3 female 26.0 0 0 7.9250 S Third woman False NaN

3 1 1 female 35.0 1 0 53.1000 S First woman False C

4 0 3 male 35.0 0 0 8.0500 S Third man True NaN

In [16]: # As you can see the filtering in titanic dataset of in sex column of female

df[df["sex"] =="female"]

Out[16]: survived pclass sex age sibsp parch fare embarked class who adult_male de

1 1 1 female 38.0 1 0 71.2833 C First woman False

2 1 3 female 26.0 0 0 7.9250 S Third woman False N

3 1 1 female 35.0 1 0 53.1000 S First woman False

8 1 3 female 27.0 0 2 11.1333 S Third woman False N

9 1 2 female 14.0 1 0 30.0708 C Second child False N

... ... ... ... ... ... ... ... ... ... ... ...

880 1 2 female 25.0 0 1 26.0000 S Second woman False N

882 0 3 female 22.0 0 0 10.5167 S Third woman False N

885 0 3 female 39.0 0 5 29.1250 Q Third woman False N

887 1 1 female 19.0 0 0 30.0000 S First woman False

888 0 3 female NaN 1 2 23.4500 S Third woman False N

314 rows × 15 columns

In [21]: df[(df["who"] == "woman") & (df["class"]== "First")]

localhost:8888/doc/tree/OneDrive/Desktop/PYTHON'S FILES/NUMPY.ipynb 64/80


1/13/24, 10:51 AM NUMPY

Out[21]: survived pclass sex age sibsp parch fare embarked class who adult_male dec

1 1 1 female 38.0 1 0 71.2833 C First woman False

3 1 1 female 35.0 1 0 53.1000 S First woman False

11 1 1 female 58.0 0 0 26.5500 S First woman False

31 1 1 female NaN 1 0 146.5208 C First woman False

52 1 1 female 49.0 1 0 76.7292 C First woman False

... ... ... ... ... ... ... ... ... ... ... ...

856 1 1 female 45.0 1 1 164.8667 S First woman False Na

862 1 1 female 48.0 0 0 25.9292 S First woman False

871 1 1 female 47.0 1 1 52.5542 S First woman False

879 1 1 female 56.0 0 1 83.1583 C First woman False

887 1 1 female 19.0 0 0 30.0000 S First woman False

91 rows × 15 columns

In [23]: df[(df["class"] == "First") & (df["survived"] == 1) & (df["embark_town"] == "Southampt

Out[23]: survived pclass sex age sibsp parch fare embarked class who adult_male dec

3 1 1 female 35.0 1 0 53.1000 S First woman False

11 1 1 female 58.0 0 0 26.5500 S First woman False

23 1 1 male 28.0 0 0 35.5000 S First man True

55 1 1 male NaN 0 0 35.5000 S First man True

88 1 1 female 23.0 3 2 263.0000 S First woman False

... ... ... ... ... ... ... ... ... ... ... ...

856 1 1 female 45.0 1 1 164.8667 S First woman False Na

857 1 1 male 51.0 0 0 26.5500 S First man True

862 1 1 female 48.0 0 0 25.9292 S First woman False

871 1 1 female 47.0 1 1 52.5542 S First woman False

887 1 1 female 19.0 0 0 30.0000 S First woman False

74 rows × 15 columns

Array Concatination
Vertical Concatination
Horizontal Concatination

localhost:8888/doc/tree/OneDrive/Desktop/PYTHON'S FILES/NUMPY.ipynb 65/80


1/13/24, 10:51 AM NUMPY

Syntax

np.concatenate((x,y) , axis = 0,1)

In [24]: a = np.arange(24).reshape(4,6)
a

array([[ 0, 1, 2, 3, 4, 5],
Out[24]:
[ 6, 7, 8, 9, 10, 11],
[12, 13, 14, 15, 16, 17],
[18, 19, 20, 21, 22, 23]])

In [26]: a.shape

(4, 6)
Out[26]:

In [27]: b = np.arange(6).reshape(1,6)
b

array([[0, 1, 2, 3, 4, 5]])
Out[27]:

In [30]: np.concatenate((a,b) , axis = 0)

array([[ 0, 1, 2, 3, 4, 5],
Out[30]:
[ 6, 7, 8, 9, 10, 11],
[12, 13, 14, 15, 16, 17],
[18, 19, 20, 21, 22, 23],
[ 0, 1, 2, 3, 4, 5]])

As you can see in below code that why it's throwing an error because of 1-D array itcan't
concatinate with columns which is axis = 1

In [31]: np.concatenate((a,b) , axis = 1)

---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[31], line 1
----> 1 np.concatenate((a,b) , axis = 1)

File <__array_function__ internals>:200, in concatenate(*args, **kwargs)

ValueError: all the input array dimensions except for the concatenation axis must mat
ch exactly, but along dimension 0, the array at index 0 has size 4 and the array at i
ndex 1 has size 1

In [32]: a

array([[ 0, 1, 2, 3, 4, 5],
Out[32]:
[ 6, 7, 8, 9, 10, 11],
[12, 13, 14, 15, 16, 17],
[18, 19, 20, 21, 22, 23]])

Watch the shape and size of "a" array which is shape(4,6) means 4 rows and 6 columns thats
why now we have to make the another array in that suitable way

In [35]: c = np.arange(4).reshape(4,1)
print(c)

localhost:8888/doc/tree/OneDrive/Desktop/PYTHON'S FILES/NUMPY.ipynb 66/80


1/13/24, 10:51 AM NUMPY
print("------------------------------------------")
print(np.concatenate((a,c) , axis = 1))

[[0]
[1]
[2]
[3]]
------------------------------------------
[[ 0 1 2 3 4 5 0]
[ 6 7 8 9 10 11 1]
[12 13 14 15 16 17 2]
[18 19 20 21 22 23 3]]

Arthemetic Operations on Array


In [41]: arr1

array([[49, 28, 24, 25, 70, 44],


Out[41]:
[71, 74, 27, 35, 56, 22],
[35, 57, 84, 57, 55, 52],
[85, 40, 72, 28, 67, 52],
[54, 49, 81, 81, 47, 78],
[26, 66, 59, 75, 75, 69]])

In [42]: arr1+5

array([[54, 33, 29, 30, 75, 49],


Out[42]:
[76, 79, 32, 40, 61, 27],
[40, 62, 89, 62, 60, 57],
[90, 45, 77, 33, 72, 57],
[59, 54, 86, 86, 52, 83],
[31, 71, 64, 80, 80, 74]])

In [43]: arr1//3

array([[16, 9, 8, 8, 23, 14],


Out[43]:
[23, 24, 9, 11, 18, 7],
[11, 19, 28, 19, 18, 17],
[28, 13, 24, 9, 22, 17],
[18, 16, 27, 27, 15, 26],
[ 8, 22, 19, 25, 25, 23]], dtype=int32)

In [44]: arr1*5

array([[245, 140, 120, 125, 350, 220],


Out[44]:
[355, 370, 135, 175, 280, 110],
[175, 285, 420, 285, 275, 260],
[425, 200, 360, 140, 335, 260],
[270, 245, 405, 405, 235, 390],
[130, 330, 295, 375, 375, 345]])

In [45]: arr1%4

array([[1, 0, 0, 1, 2, 0],
Out[45]:
[3, 2, 3, 3, 0, 2],
[3, 1, 0, 1, 3, 0],
[1, 0, 0, 0, 3, 0],
[2, 1, 1, 1, 3, 2],
[2, 2, 3, 3, 3, 1]], dtype=int32)

localhost:8888/doc/tree/OneDrive/Desktop/PYTHON'S FILES/NUMPY.ipynb 67/80


1/13/24, 10:51 AM NUMPY

In [47]: arr1 - 4

array([[45, 24, 20, 21, 66, 40],


Out[47]:
[67, 70, 23, 31, 52, 18],
[31, 53, 80, 53, 51, 48],
[81, 36, 68, 24, 63, 48],
[50, 45, 77, 77, 43, 74],
[22, 62, 55, 71, 71, 65]])

As you can see all these arthemetic operations are done over arrays which is basically asked
by the interviewer how these operations are handled by numpy.

That where we can say that we are using array Broadcasting.

Array Broadcasting

- When we perform some array to array operation on


an array of different size then to make the operation
possible Numpy adds some dumpy rows and dummy
columns to match the shape of both the arrays
This process is called as Array Broadcasting

NOTE : - Atleast one dimension should be same and the other dimension should be 1 in either
of the array

[[49, 28, 24, 25, 70, 44],


+ [[5,5,5,5,5,5],
[71, 74, 27, 35, 56, 22],
+ [5,5,5,5,5,5],
[35, 57, 84, 57, 55, 52],
+ [5,5,5,5,5,5],
[85, 40, 72, 28, 67, 52],
+ [5,5,5,5,5,5],
[54, 49, 81, 81, 47, 78],
+ [5,5,5,5,5,5],
[26, 66, 59, 75, 75, 69]]
+ [5,5,5,5,5,5]]

In [49]: arr1 + 5

array([[54, 33, 29, 30, 75, 49],


Out[49]:
[76, 79, 32, 40, 61, 27],
[40, 62, 89, 62, 60, 57],
[90, 45, 77, 33, 72, 57],
[59, 54, 86, 86, 52, 83],
[31, 71, 64, 80, 80, 74]])

Iterate over an Array

localhost:8888/doc/tree/OneDrive/Desktop/PYTHON'S FILES/NUMPY.ipynb 68/80


1/13/24, 10:51 AM NUMPY

In [50]: w = np.arange(24)
w

array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,


Out[50]:
17, 18, 19, 20, 21, 22, 23])

In [51]: for i in w:
print(i)

0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

In [52]: arr1

array([[49, 28, 24, 25, 70, 44],


Out[52]:
[71, 74, 27, 35, 56, 22],
[35, 57, 84, 57, 55, 52],
[85, 40, 72, 28, 67, 52],
[54, 49, 81, 81, 47, 78],
[26, 66, 59, 75, 75, 69]])

In [56]: for i in arr1:


print(i)
print("-------------------")

# As you can se that it is only giving lists of arrays in iterating not giving an elem

localhost:8888/doc/tree/OneDrive/Desktop/PYTHON'S FILES/NUMPY.ipynb 69/80


1/13/24, 10:51 AM NUMPY
[49 28 24 25 70 44]
-------------------
[71 74 27 35 56 22]
-------------------
[35 57 84 57 55 52]
-------------------
[85 40 72 28 67 52]
-------------------
[54 49 81 81 47 78]
-------------------
[26 66 59 75 75 69]
-------------------

As you can see it is not giving elements over an iteration so we have a function for that in
numpy which is known as np.nditer()

np.nditer()
It returns an iterable object.

In [57]: arr1

array([[49, 28, 24, 25, 70, 44],


Out[57]:
[71, 74, 27, 35, 56, 22],
[35, 57, 84, 57, 55, 52],
[85, 40, 72, 28, 67, 52],
[54, 49, 81, 81, 47, 78],
[26, 66, 59, 75, 75, 69]])

In [59]: for i in np.nditer(arr1):


print(i, end=" ")

49 28 24 25 70 44 71 74 27 35 56 22 35 57 84 57 55 52 85 40 72 28 67 52 54 49 81 81 4
7 78 26 66 59 75 75 69

Determinant
It is used to find the determinant of the array.

Formula

det=a(ei−fh)−b(di−fg)+c(dh−eg)
Which differs to array like this:
[[a,b,c], [d,e,f],
[g,h,i]
Syntax

np.linalg.det(arr)]]

In [60]: arr1

localhost:8888/doc/tree/OneDrive/Desktop/PYTHON'S FILES/NUMPY.ipynb 70/80


1/13/24, 10:51 AM NUMPY
array([[49, 28, 24, 25, 70, 44],
Out[60]:
[71, 74, 27, 35, 56, 22],
[35, 57, 84, 57, 55, 52],
[85, 40, 72, 28, 67, 52],
[54, 49, 81, 81, 47, 78],
[26, 66, 59, 75, 75, 69]])

In [62]: np.linalg.det(arr1)

2266430643.0000033
Out[62]:

In [69]: arr2 = np.arange(9).reshape(3,3)


arr2

array([[0, 1, 2],
Out[69]:
[3, 4, 5],
[6, 7, 8]])

In [70]: np.linalg.det(arr2)

0.0
Out[70]:

In [ ]:

In [ ]:

In [ ]:

In [ ]:

In [ ]:

In [ ]:

In [ ]:

In [ ]:

In [ ]:

In [ ]:

In [ ]:

In [ ]:

In [ ]:

In [ ]:

In [ ]:

localhost:8888/doc/tree/OneDrive/Desktop/PYTHON'S FILES/NUMPY.ipynb 71/80

You might also like