0% found this document useful (0 votes)
2 views

Efficient Computing with NumPy

NumPy is a fundamental library for scientific computing in Python, providing support for large multi-dimensional arrays and matrices, along with various mathematical functions. It features fixed-size, homogeneous data types for efficiency and integrates well with other scientific Python packages. Key functionalities include array creation, mathematical operations, and array manipulation, making it widely used in data science and machine learning.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Efficient Computing with NumPy

NumPy is a fundamental library for scientific computing in Python, providing support for large multi-dimensional arrays and matrices, along with various mathematical functions. It features fixed-size, homogeneous data types for efficiency and integrates well with other scientific Python packages. Key functionalities include array creation, mathematical operations, and array manipulation, making it widely used in data science and machine learning.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 73

2/1/25, 3:40 PM 12-Numpy

NumPy Fundamentals
What is NumPy?
NumPy is the fundamental package for scientific computing in Python. It is a library that
provides support for large, multi-dimensional arrays and matrices, along with a wide
range of mathematical functions to operate on these arrays. NumPy also includes a
variety of derived objects such as masked arrays and matrices, as well as routines for fast
operations on arrays, including:

Mathematical operations
Logical operations
Shape manipulation
Sorting and selection
Input/Output
Discrete Fourier transforms
Basic linear algebra
Basic statistical operations
Random simulations and more

At the core of NumPy is the ndarray object, which encapsulates n-dimensional arrays
of homogeneous data types.

NumPy Arrays vs Python Sequences


Fixed size: NumPy arrays have a fixed size at creation, unlike Python lists which can
grow dynamically. Changing the size of an ndarray will create a new array and delete
the original one.

Homogeneous data types: The elements in a NumPy array must all be of the same
data type, which results in consistent memory size across elements.

Efficiency: NumPy arrays are more efficient for mathematical and other types of
operations on large data sets. These operations are executed more efficiently and
with less code than is possible with Python's built-in sequences.

Scientific and mathematical integration: A growing number of scientific and


mathematical Python packages use NumPy arrays. Although they typically support
Python-sequence input, they convert such input to NumPy arrays before processing,
and they often output NumPy arrays.

Key Features of NumPy

file:///C:/Users/goura/Downloads/12-Numpy.html 1/73
2/1/25, 3:40 PM 12-Numpy

N-dimensional array: NumPy provides the ndarray object, a fast and flexible
container for large data sets.

Vectorization: NumPy enables element-wise operations on arrays, reducing the


need for explicit loops and making code cleaner and faster.

Mathematical functions: NumPy includes a wide range of functions for linear


algebra, statistics, and random number generation.

Efficient memory management: NumPy arrays are more memory-efficient and


faster than Python lists due to their fixed size and homogeneous data type.

Interoperability: NumPy integrates well with other Python libraries like SciPy and
Pandas.

NumPy is widely used in fields like data science, machine learning, and scientific
computing for its efficiency and extensive functionality.

Creating Numpy Arrays


In [1]: import numpy as np

a = np.array([1,2,3,4,5])
print(type(a))
a

<class 'numpy.ndarray'>
Out[1]: array([1, 2, 3, 4, 5])

In [2]: # Creating a 2D NumPy array


b = np.array([[1, 2, 3], [4, 5, 6]])

print(b)

[[1 2 3]
[4 5 6]]

In [3]: # Creating a 3D NumPy array

c = np.array([[[1,2],[3,4],[5,6],[7,8]]])
print(c)

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

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

[[[1 2]
[3 4]]

[[5 6]
[7 8]]]

file:///C:/Users/goura/Downloads/12-Numpy.html 2/73
2/1/25, 3:40 PM 12-Numpy

In [5]: # Creating a NumPy array with a specified data type (bool)


np.array([1, 2, 3], dtype=bool)

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

In [6]: # Creating a NumPy array with values from 1 to 10, with a step of 2
np.arange(1, 11, 2)

Out[6]: array([1, 3, 5, 7, 9])

In [7]: # Creating a NumPy array with values from 1 to 10 and reshaping it into a 5x2 ma
np.arange(1, 11).reshape(5, 2)

Out[7]: array([[ 1, 2],


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

In [8]: # Creating a NumPy array of shape 3x4 filled with ones


np.ones((3, 4))

Out[8]: array([[1., 1., 1., 1.],


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

In [9]: # Creating a NumPy array of shape 2x5 filled with zeros


np.zeros((2, 5))

Out[9]: array([[0., 0., 0., 0., 0.],


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

In [10]: # Creating a 3x4 NumPy array with random values between 0 and 1
np.random.random((3, 4))

Out[10]: array([[0.54255722, 0.07907659, 0.39573544, 0.97863414],


[0.57061972, 0.79350617, 0.51045827, 0.58292525],
[0.99614288, 0.38112566, 0.57266395, 0.97168837]])

In [11]: # Creating a NumPy array of 10 evenly spaced values between -10 and 10
np.linspace(-10, 10, 10)

Out[11]: array([-10. , -7.77777778, -5.55555556, -3.33333333,


-1.11111111, 1.11111111, 3.33333333, 5.55555556,
7.77777778, 10. ])

In [12]: # Creating a 3x3 identity matrix


np.identity(3)

Out[12]: array([[1., 0., 0.],


[0., 1., 0.],
[0., 0., 1.]])

Array Attributes
In [15]: # Creating three NumPy arrays with different shapes and data types
a1 = np.arange(10, dtype=np.int32) # 1D array of integers from 0 to 9
a2 = np.arange(12, dtype=float).reshape(3, 4) # 2D array (3x4) of floats

file:///C:/Users/goura/Downloads/12-Numpy.html 3/73
2/1/25, 3:40 PM 12-Numpy

a3 = np.arange(8).reshape(2, 2, 2) # 3D array (2x2x2) of integers


print("a1:-> ",a1)
print("a2:-> ",a2)
print("a3:-> ",a3)

a1:-> [0 1 2 3 4 5 6 7 8 9]
a2:-> [[ 0. 1. 2. 3.]
[ 4. 5. 6. 7.]
[ 8. 9. 10. 11.]]
a3:-> [[[0 1]
[2 3]]

[[4 5]
[6 7]]]

In [16]: # Checking the number of dimensions of the array 'a3'


a3.ndim

Out[16]: 3

In [17]: # Checking the shape of the array 'a1'


a1.shape

Out[17]: (10,)

In [18]: # Checking the size (number of elements) of the array 'a2'


print(a2.size)

12

In [19]: # Checking the size (in bytes) of each element in the array 'a1'
a1.itemsize

Out[19]: 4

In [20]: # Displaying the data types (dtype) of arrays 'a1', 'a2', and 'a3'
print(a1.dtype)
print(a2.dtype)
print(a3.dtype)

int32
float64
int32

Changing Datatype

In [21]: # astype

a2.astype(np.int32)

Out[21]: array([[ 0, 1, 2, 3],


[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])

Array Operations

In [23]: # Creating and reshaping two 3x4 arrays using np.arange


a1 = np.arange(12).reshape(3, 4)
a2 = np.arange(12, 24).reshape(3, 4)

file:///C:/Users/goura/Downloads/12-Numpy.html 4/73
2/1/25, 3:40 PM 12-Numpy

a2

Out[23]: array([[12, 13, 14, 15],


[16, 17, 18, 19],
[20, 21, 22, 23]])

In [24]: # Scalar Operation: Arithmetic - Squaring each element of 'a2'


a2**2 # Each element of the 'a2' array is squared, element-wise

Out[24]: array([[144, 169, 196, 225],


[256, 289, 324, 361],
[400, 441, 484, 529]])

In [25]: # Relational Operation: Checking if elements of 'a2' are greater than 10


a2 > 10 # Returns a boolean array indicating whether each element is greater th

Out[25]: array([[ True, True, True, True],


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

In [26]: # Vector Operation: Element-wise multiplication between 'a1' and 'a2'


a1 * a2 # Multiplies corresponding elements of 'a1' and 'a2' (element-wise)

Out[26]: array([[ 0, 13, 28, 45],


[ 64, 85, 108, 133],
[160, 189, 220, 253]])

Array Function

In [27]: # Generate a 3x3 matrix of random values between 0 and 1, then multiply by 100 a
a1 = np.random.random((3,3)) # Create a 3x3 matrix with random values
a1 = np.round(a1 * 100) # Multiply by 100 and round the values to nearest integ
a1

Out[27]: array([[35., 35., 19.],


[29., 35., 30.],
[92., 67., 6.]])

In [29]: # Find the maximum value in the entire array


print(np.max(a1))

# Find the minimum value in the entire array


print(np.min(a1))

# Find the sum of all elements in the array


print(np.sum(a1))

# Find the product of all elements in the array


print(np.prod(a1))

# Find the maximum value along rows (axis = 1)


print(np.max(a1, axis = 1))

# Find the maximum value along columns (axis = 0)


print(np.max(a1, axis = 0))

file:///C:/Users/goura/Downloads/12-Numpy.html 5/73
2/1/25, 3:40 PM 12-Numpy

92.0
6.0
348.0
26211439170000.0
[35. 35. 92.]
[92. 67. 30.]

In [31]: # Find the mean (average) of all elements in the array


print(np.mean(a1))

# Find the median of all elements in the array


print(np.median(a1))

# Find the standard deviation of all elements in the array


print(np.std(a1))

# Find the variance of all elements in the array


print(np.var(a1))

38.666666666666664
35.0
24.289915602982237
590.0

In [32]: # trigonometric functions

np.sin(a1)

Out[32]: array([[-0.42818267, -0.42818267, 0.14987721],


[-0.66363388, -0.42818267, -0.98803162],
[-0.77946607, -0.85551998, -0.2794155 ]])

In [33]: # Dot product


# The dot product of two arrays is computed using np.dot()
# It returns the matrix product of two arrays

a2 = np.arange(12).reshape(3,4) # Creates a 3x4 matrix from 0 to 11


a3 = np.arange(12,24).reshape(4,3) # Creates a 4x3 matrix from 12 to 23

np.dot(a2, a3)

Out[33]: array([[114, 120, 126],


[378, 400, 422],
[642, 680, 718]])

In [34]: # Log and Exponents


# np.log() computes the natural logarithm (base e) of all elements in the array
# np.exp() computes the exponent (e^x) of all elements in the array

np.log(a1) # Logarithm of elements in a1


np.exp(a1) # Exponential of elements in a1

Out[34]: array([[1.58601345e+15, 1.58601345e+15, 1.78482301e+08],


[3.93133430e+12, 1.58601345e+15, 1.06864746e+13],
[9.01762841e+39, 1.25236317e+29, 4.03428793e+02]])

In [35]: # round/ floor/ ceil

np.round(np.random.random((2,3))*100)

file:///C:/Users/goura/Downloads/12-Numpy.html 6/73
2/1/25, 3:40 PM 12-Numpy

np.floor(np.random.random((2,3))*100)
np.ceil(np.random.random((2,3))*100)

Out[35]: array([[ 7., 97., 56.],


[58., 56., 47.]])

Indexing and Slicing


In [36]: a1 = np.arange(10)
a2 = np.arange(12).reshape(3,4)
a3 = np.arange(8).reshape(2,2,2)

In [37]: a1

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

In [38]: a2

Out[38]: array([[ 0, 1, 2, 3],


[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])

In [39]: a3

Out[39]: array([[[0, 1],


[2, 3]],

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

In [43]: # Accessing the 5th element (index 4) from the 1D array a1


a1[4]

Out[43]: 4

In [44]: # Accessing the element at row 1, column 2 from the 2D array a2


a2[1, 2]

Out[44]: 6

In [45]: # Accessing the element at row 2, column 3 from the 2D array a2

a2[2,3]

Out[45]: 11

In [46]: # Accessing the element at index (1, 0, 1) from the 3D array a3


a3[1, 0, 1]

Out[46]: 5

In [47]: # Slicing the 1D array a1 from index 2 to 5 with a step size of 2


a1[2:5:2]

Out[47]: array([2, 4])

file:///C:/Users/goura/Downloads/12-Numpy.html 7/73
2/1/25, 3:40 PM 12-Numpy

In [48]: # Slicing the 2D array a2 to select the first row (index 0)


a2[0:1]

Out[48]: array([[0, 1, 2, 3]])

In [49]: # Slicing the 2D array a2 to select rows from index 1 onwards and columns from i
a2[1:, 1:3]

Out[49]: array([[ 5, 6],


[ 9, 10]])

In [50]: # Slicing the 2D array a2 to select every second row (::2) and every third colum
a2[::2, ::3]

Out[50]: array([[ 0, 3],


[ 8, 11]])

In [51]: # Slicing the 2D array a2 to select every second row (::2) and every second colu
a2[::2, 1::2]

Out[51]: array([[ 1, 3],


[ 9, 11]])

In [52]: # Creating a 3D array 'a3' with shape (3, 3, 3) using np.arange and reshaping it
a3 = np.arange(27).reshape(3,3,3)
a3

Out[52]: 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]]])

In [53]: a3[1]

Out[53]: array([[ 9, 10, 11],


[12, 13, 14],
[15, 16, 17]])

In [54]: a3[::2]

Out[54]: array([[[ 0, 1, 2],


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

[[18, 19, 20],


[21, 22, 23],
[24, 25, 26]]])

In [55]: a3[0,1]

Out[55]: array([3, 4, 5])

file:///C:/Users/goura/Downloads/12-Numpy.html 8/73
2/1/25, 3:40 PM 12-Numpy

In [56]: # Accessing the second row (index 1) of the 3D array 'a3', selecting all columns
a3[1,:,1]

Out[56]: array([10, 13, 16])

In [57]: a3[2,1:,1:]

Out[57]: array([[22, 23],


[25, 26]])

In [58]: a3[::2,0,::2]

Out[58]: array([[ 0, 2],


[18, 20]])

Iterating
In [59]: # Iterating over each element in the 1D array 'a1' and printing each element
for i in a1:
print(i)

0
1
2
3
4
5
6
7
8
9

In [60]: for i in a2:


print(i)

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

In [61]: for i in a3:


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]
[24 25 26]]

In [62]: # Iterating over each element in the 3D array 'a3' using nditer and printing eac
for i in np.nditer(a3):
print(i)

file:///C:/Users/goura/Downloads/12-Numpy.html 9/73
2/1/25, 3:40 PM 12-Numpy

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

Reshaping
In [63]: # Transposing the 2D array 'a2' using np.transpose and a2.T
np.transpose(a2)
a2.T

Out[63]: array([[ 0, 4, 8],


[ 1, 5, 9],
[ 2, 6, 10],
[ 3, 7, 11]])

In [64]: # Flattening the 2D array 'a2' into a 1D array using ravel()


a2.ravel()

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

In [65]: a3

Out[65]: 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]]])

file:///C:/Users/goura/Downloads/12-Numpy.html 10/73
2/1/25, 3:40 PM 12-Numpy

In [66]: # Flattening the 3D array 'a3' into a 1D array using ravel()


a3.ravel()

Out[66]: 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])

Stacking
In [67]: # Horizontal Stacking

a4 = np.arange(12).reshape(3,4)
a5 = np.arange(12,24).reshape(3,4)

In [68]: a4

Out[68]: array([[ 0, 1, 2, 3],


[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])

In [69]: a5

Out[69]: array([[12, 13, 14, 15],


[16, 17, 18, 19],
[20, 21, 22, 23]])

In [70]: # Horizontally stacking two arrays 'a4' and 'a5'


np.hstack((a4, a5))

Out[70]: array([[ 0, 1, 2, 3, 12, 13, 14, 15],


[ 4, 5, 6, 7, 16, 17, 18, 19],
[ 8, 9, 10, 11, 20, 21, 22, 23]])

In [71]: # Horizontally stacking multiple arrays 'a4', 'a5', 'a4', and 'a5'
np.hstack((a4, a5, a4, a5))

Out[71]: array([[ 0, 1, 2, 3, 12, 13, 14, 15, 0, 1, 2, 3, 12, 13, 14, 15],
[ 4, 5, 6, 7, 16, 17, 18, 19, 4, 5, 6, 7, 16, 17, 18, 19],
[ 8, 9, 10, 11, 20, 21, 22, 23, 8, 9, 10, 11, 20, 21, 22, 23]])

In [74]: # Vertically stacking arrays 'a4' and 'a5'


np.vstack((a4, a5))

Out[74]: 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]])

Splitting
In [73]: a4

file:///C:/Users/goura/Downloads/12-Numpy.html 11/73
2/1/25, 3:40 PM 12-Numpy

Out[73]: array([[ 0, 1, 2, 3],


[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])

In [75]: # Horizontally splitting array 'a4' into 2 equal parts


np.hsplit(a4, 2)

Out[75]: [array([[0, 1],


[4, 5],
[8, 9]]),
array([[ 2, 3],
[ 6, 7],
[10, 11]])]

In [76]: # Attempting to horizontally split array 'a4' into 5 equal parts


np.hsplit(a4, 5) # This will raise an error if a4's number of columns isn't divi

---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[76], line 2
1 # Attempting to horizontally split array 'a4' into 5 equal parts
----> 2 np.hsplit(a4, 5)

File ~\anaconda3\Lib\site-packages\numpy\lib\shape_base.py:938, in hsplit(ary, in


dices_or_sections)
936 raise ValueError('hsplit only works on arrays of 1 or more dimension
s')
937 if ary.ndim > 1:
--> 938 return split(ary, indices_or_sections, 1)
939 else:
940 return split(ary, indices_or_sections, 0)

File ~\anaconda3\Lib\site-packages\numpy\lib\shape_base.py:864, in split(ary, ind


ices_or_sections, axis)
862 N = ary.shape[axis]
863 if N % sections:
--> 864 raise ValueError(
865 'array split does not result in an equal division') from None
866 return array_split(ary, indices_or_sections, axis)

ValueError: array split does not result in an equal division

In [77]: # Vertical Splitting

a5

Out[77]: array([[12, 13, 14, 15],


[16, 17, 18, 19],
[20, 21, 22, 23]])

In [78]: # Attempting to vertically split array 'a5' into 3 equal parts


np.vsplit(a5, 3)

Out[78]: [array([[12, 13, 14, 15]]),


array([[16, 17, 18, 19]]),
array([[20, 21, 22, 23]])]

In [79]: # Splitting array 'a5' vertically into 2 equal parts


np.vsplit(a5, 2) # This will work only if a5's number of rows is divisible by 2

file:///C:/Users/goura/Downloads/12-Numpy.html 12/73
2/1/25, 3:40 PM 12-Numpy

---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[79], line 2
1 # Splitting array 'a5' vertically into 2 equal parts
----> 2 np.vsplit(a5, 2)

File ~\anaconda3\Lib\site-packages\numpy\lib\shape_base.py:989, in vsplit(ary, in


dices_or_sections)
987 if _nx.ndim(ary) < 2:
988 raise ValueError('vsplit only works on arrays of 2 or more dimension
s')
--> 989 return split(ary, indices_or_sections, 0)

File ~\anaconda3\Lib\site-packages\numpy\lib\shape_base.py:864, in split(ary, ind


ices_or_sections, axis)
862 N = ary.shape[axis]
863 if N % sections:
--> 864 raise ValueError(
865 'array split does not result in an equal division') from None
866 return array_split(ary, indices_or_sections, axis)

ValueError: array split does not result in an equal division

Advanced Numpy
Numpy array vs Python List

In [9]: # Measuring execution time for summing two lists element-wise

import time

# Creating two large lists


a = [i for i in range(10000000)]
b = [i for i in range(10000000, 20000000)]

# Start time
start = time.time()

# Element-wise addition of two lists


c = []
for i in range(len(a)):
c.append(a[i] + b[i])

# End time and print elapsed time


print(time.time() - start)

3.600071907043457

In [10]: # Measuring execution time for summing two NumPy arrays element-wise

import numpy as np
import time

# Creating two large NumPy arrays


a = np.arange(10000000)
b = np.arange(10000000, 20000000)

# Start time

file:///C:/Users/goura/Downloads/12-Numpy.html 13/73
2/1/25, 3:40 PM 12-Numpy

start = time.time()

# Element-wise addition of two NumPy arrays


c = a + b

# End time and print elapsed time


print(time.time() - start)

0.19878029823303223

In [11]: 3.60/0.19

Out[11]: 18.94736842105263

In [12]: # Measuring memory usage of a Python list

import sys

# Creating a large Python list


a = [i for i in range(10000000)]

# Getting the memory size of the list in bytes


print(sys.getsizeof(a))

89095160

In [5]: a = np.arange(10000000)
sys.getsizeof(a)

Out[5]: 40000112

In [6]: a = np.arange(10000000, dtype = np.int16)


sys.getsizeof(a)

Out[6]: 20000112

Advance Indexing
In [14]: # Advance indexing and slicing

a = np.arange(12).reshape(4,3)
a

Out[14]: array([[ 0, 1, 2],


[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11]])

In [15]: # Fancy indexing


a[[0,2,3]]

Out[15]: array([[ 0, 1, 2],


[ 6, 7, 8],
[ 9, 10, 11]])

In [16]: b = np.arange(24).reshape(6,4)
b

file:///C:/Users/goura/Downloads/12-Numpy.html 14/73
2/1/25, 3:40 PM 12-Numpy

Out[16]: 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]])

In [19]: # Accessing elements at indices 0, 2, 3, and 5 from the NumPy array `b`
b[[0, 2, 3, 5]]

Out[19]: array([[ 0, 1, 2, 3],


[ 8, 9, 10, 11],
[12, 13, 14, 15],
[20, 21, 22, 23]])

In [20]: # Attempting to access specific columns (0, 2, 3) from all rows of a 2D NumPy ar
b[:, [0, 2, 3]]

Out[20]: array([[ 0, 2, 3],


[ 4, 6, 7],
[ 8, 10, 11],
[12, 14, 15],
[16, 18, 19],
[20, 22, 23]])

In [21]: # Boolean Indexing

a = np.random.randint(1,100,24).reshape(6,4)
a

Out[21]: array([[86, 78, 20, 4],


[38, 91, 77, 74],
[13, 46, 91, 42],
[29, 9, 94, 63],
[36, 22, 23, 73],
[85, 86, 48, 52]])

In [22]: # Find all number Greater then 50

a>50

Out[22]: array([[ True, True, False, False],


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

In [23]: # filter

a[a>50]

Out[23]: array([86, 78, 91, 77, 74, 91, 94, 63, 73, 85, 86, 52])

In [24]: # Find out even numbers

a%2 == 0

file:///C:/Users/goura/Downloads/12-Numpy.html 15/73
2/1/25, 3:40 PM 12-Numpy

Out[24]: array([[ True, True, True, True],


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

In [25]: a[a%2 == 0]

Out[25]: array([86, 78, 20, 4, 38, 74, 46, 42, 94, 36, 22, 86, 48, 52])

In [26]: # find out all numbers greater then 50 and are even

# whenever you work with boolean number use bitwise operation (&) != (and)
(a>50) & (a%2 == 0)

Out[26]: array([[ True, True, False, False],


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

In [27]: a[(a>50) & (a%2 == 0)]

Out[27]: array([86, 78, 74, 94, 86, 52])

In [28]: # find all numbers not divisivle by 7

a[~(a % 7== 0)]

Out[28]: array([86, 78, 20, 4, 38, 74, 13, 46, 29, 9, 94, 36, 22, 23, 73, 85, 86,
48, 52])

In [29]: a[a % 7 != 0]

Out[29]: array([86, 78, 20, 4, 38, 74, 13, 46, 29, 9, 94, 36, 22, 23, 73, 85, 86,
48, 52])

Broadcasting
The term broadcasting describes how NumPy treats arrays with different shapes during
arithmetic operations.

The smaller array is “broadcast” across the larger array so that they have compatible
shapes.

In [30]: # Same Shape

a = np.arange(6).reshape(2,3)
b = np.arange(6,12).reshape(2,3)

print(a)
print(b)

file:///C:/Users/goura/Downloads/12-Numpy.html 16/73
2/1/25, 3:40 PM 12-Numpy

print(a+b)

[[0 1 2]
[3 4 5]]
[[ 6 7 8]
[ 9 10 11]]
[[ 6 8 10]
[12 14 16]]

In [31]: a = np.arange(6).reshape(2,3)
b = np.arange(3).reshape(1,3)

print(a)
print(b)

print(a+b)

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

Broadcasting Rules

1. Make the two arrays have the same number of dimensions.

If the numbers of dimensions of the two arrays are different, add new dimensions with
size 1 to the head of the array with the smaller dimension.

2. Make each dimension of the two arrays the same size.

If the sizes of each dimension of the two arrays do not match, dimensions with size 1 are
stretched to the size of the other array. If there is a dimension whose size is not 1 in
either of the two arrays, it cannot be broadcasted, and an error is raised.

file:///C:/Users/goura/Downloads/12-Numpy.html 17/73
2/1/25, 3:40 PM 12-Numpy

In [34]: # Broadcasting example in NumPy

# Creating a 2D array 'a' with shape (4, 3)


a = np.arange(12).reshape(4, 3)

# Creating a 1D array 'b' with shape (3,)


b = np.arange(3)

# Printing both arrays


print(a)
print(b)
print('********')

# Adding arrays 'a' and 'b' using broadcasting


# The 1D array 'b' is broadcasted to match the shape of 'a' for element-wise add
print(a + b)

[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]
[ 9 10 11]]
[0 1 2]
********
[[ 0 2 4]
[ 3 5 7]
[ 6 8 10]
[ 9 11 13]]

In [35]: # Broadcasting example with incompatible shapes in NumPy

a = np.arange(12).reshape(3, 4)
b = np.arange(3)

print(a)
print(b)

# Attempting to add arrays 'a' and 'b'


# This will raise a ValueError because the shapes (3, 4) and (3,) are incompatib
print(a + b)

[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
[0 1 2]
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[35], line 11
7 print(b) # Printing the 1D array
9 # Attempting to add arrays 'a' and 'b'
10 # This will raise a ValueError because the shapes (3, 4) and (3,) are inc
ompatible for broadcasting
---> 11 print(a + b)

ValueError: operands could not be broadcast together with shapes (3,4) (3,)

In [36]: # Broadcasting example in NumPy with compatible shapes

a = np.arange(3).reshape(1, 3)
b = np.arange(3).reshape(3, 1)

file:///C:/Users/goura/Downloads/12-Numpy.html 18/73
2/1/25, 3:40 PM 12-Numpy

print(a)
print(b)

# Adding arrays 'a' and 'b' using broadcasting


# The shapes (1, 3) and (3, 1) are broadcastable to a common shape (3, 3)
print(a + b) # Element-wise addition results in a 3x3 matrix

[[0 1 2]]
[[0]
[1]
[2]]
[[0 1 2]
[1 2 3]
[2 3 4]]

In [37]: # Broadcasting example with arrays of shapes (1, 3) and (4, 1)

a = np.arange(3).reshape(1, 3)
b = np.arange(4).reshape(4, 1)

print(a)
print(b)

# Adding arrays 'a' and 'b' using broadcasting


# The shapes (1, 3) and (4, 1) are broadcastable to a common shape (4, 3)
print(a + b) # Element-wise addition results in a 4x3 matrix

[[0 1 2]]
[[0]
[1]
[2]
[3]]
[[0 1 2]
[1 2 3]
[2 3 4]
[3 4 5]]

In [39]: # Array a with shape (3, 4)


a = np.arange(12).reshape(3, 4)

# Array b with shape (4, 3)


b = np.arange(12).reshape(4, 3)

print(a)
print(b)

print(a+b) # Attempting to add the two arrays together will raise a ValueError

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

file:///C:/Users/goura/Downloads/12-Numpy.html 19/73
2/1/25, 3:40 PM 12-Numpy

---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[39], line 10
7 print(a) # Printing the first array (shape 3x4)
8 print(b) # Printing the second array (shape 4x3)
---> 10 print(a+b)

ValueError: operands could not be broadcast together with shapes (3,4) (4,3)

In [40]: # Array a with shape (4, 4)


a = np.arange(16).reshape(4, 4)

# Array b with shape (2, 2)


b = np.arange(4).reshape(2, 2)

print(a)
print(b)

# Adding a and b directly will raise a ValueError because their shapes are incom
# The operation a + b will fail because their dimensions do not align
print(a + b) # This will raise a ValueError due to shape mismatch

[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]]
[[0 1]
[2 3]]
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[40], line 12
8 print(b) # Printing the second array (shape 2x2)
10 # Adding a and b directly will raise a ValueError because their shapes ar
e incompatible
11 # The operation a + b will fail because their dimensions do not align
---> 12 print(a + b)

ValueError: operands could not be broadcast together with shapes (4,4) (2,2)

Working with mathematical formula


In [41]: a = np.arange(10)
np.sum(a)

Out[41]: 45

In [42]: # Trigonometric
np.sin(a)

Out[42]: array([ 0. , 0.84147098, 0.90929743, 0.14112001, -0.7568025 ,


-0.95892427, -0.2794155 , 0.6569866 , 0.98935825, 0.41211849])

In [43]: # Sigmoid

def sigmoid(array):
return 1/(1+np.exp(-(array)))

file:///C:/Users/goura/Downloads/12-Numpy.html 20/73
2/1/25, 3:40 PM 12-Numpy

a = np.arange(10)
sigmoid(a)

Out[43]: array([0.5 , 0.73105858, 0.88079708, 0.95257413, 0.98201379,


0.99330715, 0.99752738, 0.99908895, 0.99966465, 0.99987661])

In [44]: # Mean squared Error

actual = np.random.randint(1,50,25)
predicted = np.random.randint(1,50,25)

In [45]: actual

Out[45]: array([ 3, 47, 12, 41, 25, 29, 3, 20, 42, 24, 45, 20, 2, 46, 7, 7, 42,
2, 34, 20, 12, 22, 44, 35, 47])

In [46]: predicted

Out[46]: array([16, 37, 47, 25, 16, 36, 15, 47, 11, 21, 39, 36, 33, 2, 48, 28, 47,
21, 14, 44, 18, 34, 13, 16, 43])

In [47]: def mse(actual,predicted):


return np.mean((actual-predicted)**2)

mse(actual,predicted)

Out[47]: 476.56

In [48]: # Binary cross Entropy

import warnings
warnings.filterwarnings('ignore')

def bce(actual,predicted):
return np.mean(-(actual*np.log(predicted))+(1-actual)*np.log(1-predicted))

bce(actual,predicted)

Out[48]: nan

Working with missing values

In [49]: # Working with missing values --> np.nan

a = np.array([1,2,3,4,5,np.nan,7,np.nan,9])
a

Out[49]: array([ 1., 2., 3., 4., 5., nan, 7., nan, 9.])

In [50]: np.isnan(a)

Out[50]: array([False, False, False, False, False, True, False, True, False])

In [51]: a[~np.isnan(a)]

file:///C:/Users/goura/Downloads/12-Numpy.html 21/73
2/1/25, 3:40 PM 12-Numpy

Out[51]: array([1., 2., 3., 4., 5., 7., 9.])

Plotting Graphs
In [52]: # Plotting a 2D Plots
#x = y
import matplotlib.pyplot as plt

x = np.linspace(-10,10,100)
y = x

plt.plot(x,y)

Out[52]: [<matplotlib.lines.Line2D at 0x1bc808e5590>]

In [53]: # y = x^2

x = np.linspace(-10,10,100)
y = x**2

plt.plot(x,y)

Out[53]: [<matplotlib.lines.Line2D at 0x1bc80938c90>]

file:///C:/Users/goura/Downloads/12-Numpy.html 22/73
2/1/25, 3:40 PM 12-Numpy

In [54]: #y = sin(x)

x = np.linspace(-10,10,100)
y = np.sin(x)

plt.plot(x,y)

Out[54]: [<matplotlib.lines.Line2D at 0x1bc80998c90>]

file:///C:/Users/goura/Downloads/12-Numpy.html 23/73
2/1/25, 3:40 PM 12-Numpy

In [55]: #y = xlogx

x = np.linspace(-10,10,100)
y = x* np.log(x)

plt.plot(x,y)

Out[55]: [<matplotlib.lines.Line2D at 0x1bc80b94d10>]

In [56]: # sigmoid
x = np.linspace(-10,10,100)
y = 1/(1+np.exp(-x))

plt.plot(x,y)

Out[56]: [<matplotlib.lines.Line2D at 0x1bc80c20050>]

file:///C:/Users/goura/Downloads/12-Numpy.html 24/73
2/1/25, 3:40 PM 12-Numpy

NUMPY TRICKS
np.sort
Return a sorted copy of an array.

In [57]: a = np.random.randint(1,100,15)
a

Out[57]: array([89, 5, 10, 40, 53, 78, 96, 53, 79, 58, 44, 58, 40, 91, 28])

In [58]: b = np.random.randint(1,100,24).reshape(6,4)
b

Out[58]: array([[97, 16, 19, 15],


[94, 34, 38, 21],
[ 8, 41, 32, 43],
[65, 1, 55, 82],
[79, 8, 5, 12],
[29, 18, 24, 2]])

In [59]: np.sort(a)

Out[59]: array([ 5, 10, 28, 40, 40, 44, 53, 53, 58, 58, 78, 79, 89, 91, 96])

In [60]: # For descending sorting

np.sort(a)[::-1]

Out[60]: array([96, 91, 89, 79, 78, 58, 58, 53, 53, 44, 40, 40, 28, 10, 5])

In [61]: np.sort(b)

file:///C:/Users/goura/Downloads/12-Numpy.html 25/73
2/1/25, 3:40 PM 12-Numpy

Out[61]: array([[15, 16, 19, 97],


[21, 34, 38, 94],
[ 8, 32, 41, 43],
[ 1, 55, 65, 82],
[ 5, 8, 12, 79],
[ 2, 18, 24, 29]])

In [62]: # For Column-wise

np.sort(b,axis = 0)

Out[62]: array([[ 8, 1, 5, 2],


[29, 8, 19, 12],
[65, 16, 24, 15],
[79, 18, 32, 21],
[94, 34, 38, 43],
[97, 41, 55, 82]])

np.append
The numpy.append() appends values along the mentioned axis at the end of the
array

In [63]: a

Out[63]: array([89, 5, 10, 40, 53, 78, 96, 53, 79, 58, 44, 58, 40, 91, 28])

In [64]: np.append(a,200)

Out[64]: array([ 89, 5, 10, 40, 53, 78, 96, 53, 79, 58, 44, 58, 40,
91, 28, 200])

In [65]: b

Out[65]: array([[97, 16, 19, 15],


[94, 34, 38, 21],
[ 8, 41, 32, 43],
[65, 1, 55, 82],
[79, 8, 5, 12],
[29, 18, 24, 2]])

In [66]: np.append(b,np.ones((b.shape[0],1)),axis = 1)

Out[66]: array([[97., 16., 19., 15., 1.],


[94., 34., 38., 21., 1.],
[ 8., 41., 32., 43., 1.],
[65., 1., 55., 82., 1.],
[79., 8., 5., 12., 1.],
[29., 18., 24., 2., 1.]])

In [67]: np.append(b,np.random.random((b.shape[0],1)),axis = 1)

Out[67]: array([[97. , 16. , 19. , 15. , 0.94918317],


[94. , 34. , 38. , 21. , 0.71893044],
[ 8. , 41. , 32. , 43. , 0.87273939],
[65. , 1. , 55. , 82. , 0.38426565],
[79. , 8. , 5. , 12. , 0.88594049],
[29. , 18. , 24. , 2. , 0.66446451]])

file:///C:/Users/goura/Downloads/12-Numpy.html 26/73
2/1/25, 3:40 PM 12-Numpy

np.concatenate
numpy.concatenate() function concatenate a sequence of arrays along an existing
axis.

In [68]: c = np.arange(6).reshape(2,3)
d = np.arange(6,12).reshape(2,3)

print(c)
print(d)

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

In [69]: np.concatenate((c,d),axis = 0)

Out[69]: array([[ 0, 1, 2],


[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11]])

In [70]: np.concatenate((c,d),axis = 1)

Out[70]: array([[ 0, 1, 2, 6, 7, 8],


[ 3, 4, 5, 9, 10, 11]])

np.unique
With the help of np.unique() method, we can get the unique values from an array
given as parameter in np.unique() method.

In [71]: e = np.array([1,2,2,3,3,3,4,4,4,4,5,5,5,5,5,6,6,6,6,6,6,7,8,8,8,9,9,0,0,7])

In [72]: np.unique(e)

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

np.expand_dims
With the help of Numpy.expand_dims() method, we can get the expanded
dimensions of an array

In [73]: a

Out[73]: array([89, 5, 10, 40, 53, 78, 96, 53, 79, 58, 44, 58, 40, 91, 28])

In [74]: # Convert 1d to 2d

np.expand_dims(a,axis=0)

Out[74]: array([[89, 5, 10, 40, 53, 78, 96, 53, 79, 58, 44, 58, 40, 91, 28]])

file:///C:/Users/goura/Downloads/12-Numpy.html 27/73
2/1/25, 3:40 PM 12-Numpy

In [75]: np.expand_dims(a,axis=0).shape

Out[75]: (1, 15)

In [76]: np.expand_dims(a,axis=1)

Out[76]: array([[89],
[ 5],
[10],
[40],
[53],
[78],
[96],
[53],
[79],
[58],
[44],
[58],
[40],
[91],
[28]])

In [77]: np.expand_dims(a,axis=1).shape

Out[77]: (15, 1)

np.where
The numpy.where() function returns the indices of elements in an input array where
the given condition is satisfied.

In [78]: a

Out[78]: array([89, 5, 10, 40, 53, 78, 96, 53, 79, 58, 44, 58, 40, 91, 28])

In [79]: # Find all the indexes value when value greater than 50

np.where(a>50)

Out[79]: (array([ 0, 4, 5, 6, 7, 8, 9, 11, 13], dtype=int64),)

In [80]: # Replace all values > 50 with 0


# np.where(condition,True,False)

np.where(a>50,0,a)

Out[80]: array([ 0, 5, 10, 40, 0, 0, 0, 0, 0, 0, 44, 0, 40, 0, 28])

In [81]: np.where(a%2 ==0,0,a)

Out[81]: array([89, 5, 0, 0, 53, 0, 0, 53, 79, 0, 0, 0, 0, 91, 0])

np.argmax

file:///C:/Users/goura/Downloads/12-Numpy.html 28/73
2/1/25, 3:40 PM 12-Numpy

The numpy.argmax() function returns indices of the max element of the array in a
particular axis.

In [82]: a

Out[82]: array([89, 5, 10, 40, 53, 78, 96, 53, 79, 58, 44, 58, 40, 91, 28])

In [83]: np.argmax(a)

Out[83]: 6

In [84]: b

Out[84]: array([[97, 16, 19, 15],


[94, 34, 38, 21],
[ 8, 41, 32, 43],
[65, 1, 55, 82],
[79, 8, 5, 12],
[29, 18, 24, 2]])

In [85]: np.argmax(b,axis = 0)

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

In [86]: np.argmax(b,axis = 1)

Out[86]: array([0, 0, 3, 3, 0, 0], dtype=int64)

In [87]: # np.argmin

np.argmin(a)

Out[87]: 1

In [88]: np.argmin(b,axis = 0)

Out[88]: array([2, 3, 4, 5], dtype=int64)

In [89]: np.argmin(b,axis = 1)

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

np.cumsum
numpy.cumsum() function is used when we want to compute the cumulative sum of
array elements over a given axis.

Moving sum

In [90]: a

Out[90]: array([89, 5, 10, 40, 53, 78, 96, 53, 79, 58, 44, 58, 40, 91, 28])

In [91]: np.cumsum(a)

file:///C:/Users/goura/Downloads/12-Numpy.html 29/73
2/1/25, 3:40 PM 12-Numpy

Out[91]: array([ 89, 94, 104, 144, 197, 275, 371, 424, 503, 561, 605, 663, 703,
794, 822])

In [92]: b

Out[92]: array([[97, 16, 19, 15],


[94, 34, 38, 21],
[ 8, 41, 32, 43],
[65, 1, 55, 82],
[79, 8, 5, 12],
[29, 18, 24, 2]])

In [93]: np.cumsum(b)

Out[93]: array([ 97, 113, 132, 147, 241, 275, 313, 334, 342, 383, 415, 458, 523,
524, 579, 661, 740, 748, 753, 765, 794, 812, 836, 838])

In [94]: np.cumsum(b, axis = 0)

Out[94]: array([[ 97, 16, 19, 15],


[191, 50, 57, 36],
[199, 91, 89, 79],
[264, 92, 144, 161],
[343, 100, 149, 173],
[372, 118, 173, 175]])

In [95]: np.cumsum(b,axis = 1)

Out[95]: array([[ 97, 113, 132, 147],


[ 94, 128, 166, 187],
[ 8, 49, 81, 124],
[ 65, 66, 121, 203],
[ 79, 87, 92, 104],
[ 29, 47, 71, 73]])

In [96]: # np.cumprod

np.cumprod(a)

Out[96]: array([ 89, 445, 4450, 178000, 9434000,


735852000, 1922315264, -1196506112, -34702336, -2012735488,
1633951744, 279920640, -1688076288, 1003880448, -1956118528])

np.percentile
numpy.percentile()function used to compute the nth percentile of the given data
(array elements) along the specified axis.

In [97]: a

Out[97]: array([89, 5, 10, 40, 53, 78, 96, 53, 79, 58, 44, 58, 40, 91, 28])

In [98]: np.percentile(a,100)

Out[98]: 96.0

In [99]: np.percentile(a,0)

file:///C:/Users/goura/Downloads/12-Numpy.html 30/73
2/1/25, 3:40 PM 12-Numpy

Out[99]: 5.0

In [100… np.percentile(a,50)

Out[100… 53.0

In [101… np.median(a)

Out[101… 53.0

np.histogram
Numpy has a built-in numpy.histogram() function which represents the frequency of
data distribution in the graphical form.

In [102… a

Out[102… array([89, 5, 10, 40, 53, 78, 96, 53, 79, 58, 44, 58, 40, 91, 28])

In [103… np.histogram(a,bins =[0,10,20,30,40,50,60,70,80,90,100])

Out[103… (array([1, 1, 1, 0, 3, 4, 0, 2, 1, 2], dtype=int64),


array([ 0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]))

np.corrcoef
Return Pearson product-moment correlation coefficients.

In [104… salary = np.array([20000,40000,25000,35000,60000])


experience = np.array([1,3,2,4,2])

np.corrcoef(salary,experience)

Out[104… array([[1. , 0.25344572],


[0.25344572, 1. ]])

np.isin
With the help of numpy.isin() method, we can see that one array having values are
checked in a different numpy array having different elements with different sizes.

In [105… a

Out[105… array([89, 5, 10, 40, 53, 78, 96, 53, 79, 58, 44, 58, 40, 91, 28])

In [106… items = [10,20,30,40,50,60,70,80,90,100]


np.isin(a,items)

Out[106… array([False, False, True, True, False, False, False, False, False,
False, False, False, True, False, False])

In [107… a[np.isin(a,items)]

file:///C:/Users/goura/Downloads/12-Numpy.html 31/73
2/1/25, 3:40 PM 12-Numpy

Out[107… array([10, 40, 40])

np.flip
The numpy.flip() function reverses the order of array elements along the specified
axis, preserving the shape of the array.

In [108… a

Out[108… array([89, 5, 10, 40, 53, 78, 96, 53, 79, 58, 44, 58, 40, 91, 28])

In [109… np.flip(a)

Out[109… array([28, 91, 40, 58, 44, 58, 79, 53, 96, 78, 53, 40, 10, 5, 89])

In [110… np.flip(b)

Out[110… array([[ 2, 24, 18, 29],


[12, 5, 8, 79],
[82, 55, 1, 65],
[43, 32, 41, 8],
[21, 38, 34, 94],
[15, 19, 16, 97]])

In [111… np.flip(b,axis = 0)

Out[111… array([[29, 18, 24, 2],


[79, 8, 5, 12],
[65, 1, 55, 82],
[ 8, 41, 32, 43],
[94, 34, 38, 21],
[97, 16, 19, 15]])

np.put
The numpy.put() function replaces specific elements of an array with given values of
p_array. Array indexed works on flattened array.

In [112… a

Out[112… array([89, 5, 10, 40, 53, 78, 96, 53, 79, 58, 44, 58, 40, 91, 28])

In [113… np.put(a,[0,1],[110,530])

In [114… a

Out[114… array([110, 530, 10, 40, 53, 78, 96, 53, 79, 58, 44, 58, 40,
91, 28])

np.delete
The numpy.delete() function returns a new array with the deletion of sub-arrays
along with the mentioned axis.

file:///C:/Users/goura/Downloads/12-Numpy.html 32/73
2/1/25, 3:40 PM 12-Numpy

In [115… a

Out[115… array([110, 530, 10, 40, 53, 78, 96, 53, 79, 58, 44, 58, 40,
91, 28])

In [116… np.delete(a,0)

Out[116… array([530, 10, 40, 53, 78, 96, 53, 79, 58, 44, 58, 40, 91,
28])

In [117… np.delete(a,[0,2,4])

Out[117… array([530, 40, 78, 96, 53, 79, 58, 44, 58, 40, 91, 28])

Set functions
np.union1d
np.intersect1d
np.setdiff1d
np.setxor1d
np.in1d

In [118… g = np.array([1,2,3,4,5])
k = np.array([3,4,5,6,7])

np.union1d(g,k)

Out[118… array([1, 2, 3, 4, 5, 6, 7])

In [119… np.intersect1d(g,k)

Out[119… array([3, 4, 5])

In [120… np.setdiff1d(g,k)

Out[120… array([1, 2])

In [121… np.setdiff1d(k,g)

Out[121… array([6, 7])

In [122… np.setxor1d(g,k)

Out[122… array([1, 2, 6, 7])

In [123… np.in1d(g,1)

Out[123… array([ True, False, False, False, False])

np.clip
numpy.clip() function is used to Clip (limit) the values in an array.

file:///C:/Users/goura/Downloads/12-Numpy.html 33/73
2/1/25, 3:40 PM 12-Numpy

In [124… a

Out[124… array([110, 530, 10, 40, 53, 78, 96, 53, 79, 58, 44, 58, 40,
91, 28])

In [125… np.clip(a,a_min = 25,a_max = 75)

Out[125… array([75, 75, 25, 40, 53, 75, 75, 53, 75, 58, 44, 58, 40, 75, 28])

In [126… # Swapping axes of a 2D array


a = np.arange(9).reshape(3, 3)
a

Out[126… array([[0, 1, 2],


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

In [127… b = np.swapaxes(a, 0, 1) # Swapping rows and columns


print(b)

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

Description: np.swapaxes swaps the specified axes of an array; in this case, swapping
the rows and columns of the 3x3 array.

In [128… # np.uniform
# Generating random values from a uniform distribution
a = np.random.uniform(0, 10, size=(3, 3)) # Generates a 3x3 array with random v
print(a) # Printing the generated array

[[4.57310052 6.11396593 3.20217049]


[9.31723476 5.69752117 9.28662625]
[4.06949986 5.53312361 7.29136521]]

Description: np.random.uniform(low, high, size) generates random values from a


uniform distribution between the specified low and high values.

In [129… # np.count_nonzero
# Counting non-zero elements in the array
a = np.array([0, 1, 2, 0, 3, 0, 4]) # Creating an array with some zero and non-
non_zero_count = np.count_nonzero(a) # Counting non-zero elements in the array
print(non_zero_count) # Printing the count of non-zero elements

Description: np.count_nonzero(a) counts the number of non-zero elements in the


array a.

In [130… # Repeating the array along specified axes


a = np.array([1, 2, 3])
tiled_a = np.tile(a, 3) # Repeating the array 3 times along the first axis
print(tiled_a) # Printing the tiled array

[1 2 3 1 2 3 1 2 3]

file:///C:/Users/goura/Downloads/12-Numpy.html 34/73
2/1/25, 3:40 PM 12-Numpy

Description: np.tile(a, 3) repeats the array a 3 times, creating a new array with the
repeated values.

In [131… # np.repeat
# Repeating elements of an array
a = np.array([1, 2, 3]) # Creating an array
repeated_a = np.repeat(a, 2) # Repeating each element of the array 2 times
print(repeated_a)

[1 1 2 2 3 3]

Description: np.repeat(a, 2) repeats each element in the array a 2 times.

In [132… # np.allclose and equals


# np.allclose checks if two arrays are element-wise equal within a tolerance
a = np.array([1.0, 2.0, 3.0])
b = np.array([1.0, 2.0000001, 3.0])

# Checking if a and b are element-wise equal within a tolerance


print(np.allclose(a, b)) # Returns True because the difference is within tolera

# np.array_equal checks if two arrays are exactly equal


c = np.array([1.0, 2.0, 3.0])
d = np.array([1.0, 2.0, 4.0])

# Checking if c and d are exactly equal


print(np.array_equal(c, d)) # Returns False because the arrays are not exactly

True
False

Description:

np.allclose(a, b) checks whether the elements of two arrays a and b are equal within
a certain tolerance.
np.array_equal(c, d) checks if two arrays c and d are exactly equal (element-wise
equality).

In [133… # Structured numpy array


import numpy as np

# Defining a structured numpy array with fields 'name' and 'age'


dtype = [('name', 'U10'), ('age', 'i4')]
values = [('Alice', 25), ('Bob', 30), ('Charlie', 35)]

# Creating a structured array


structured_array = np.array(values, dtype=dtype)

# Accessing the fields


print(structured_array['name']) # Accessing the 'name' field
print(structured_array['age']) # Accessing the 'age' field

# Printing the entire structured array


print(structured_array)

file:///C:/Users/goura/Downloads/12-Numpy.html 35/73
2/1/25, 3:40 PM 12-Numpy

['Alice' 'Bob' 'Charlie']


[25 30 35]
[('Alice', 25) ('Bob', 30) ('Charlie', 35)]

Description:

A structured numpy array allows you to store heterogeneous data, such as a


collection of different types (e.g., strings, integers) in a single array.
Each element in the structured array can have multiple fields, and each field can
have its own data type.
This is similar to a database record or a table with named columns.

In [134… # Masked Arrays


import numpy as np

# Creating a numpy array


data = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])

# Masking the array (masking values greater than 5)


masked_array = np.ma.masked_where(data > 5, data)

# Printing the masked array


print(masked_array)

# Accessing masked values


print(masked_array.mask) # Shows which values are masked

[1 2 3 4 5 -- -- -- --]
[False False False False False True True True True]

Description:

A masked array is a special kind of array in NumPy where certain elements are
"masked" or marked as invalid, and these masked values are not included in
operations.
Masked arrays are useful when you want to ignore certain data points (e.g., invalid
or missing values) during computations without affecting the overall array structure.
You can create a masked array using conditions, and the masked values will be
represented by -- (or other user-defined values).

TASK

Q-1 Create a null vector of size 10 but the fifth value which
is 1.
In [2]: #Code here
import numpy as np
# Filling the numpy array with NaN values
a = np.nan * np.empty(10)
a[4] = 1
a

Out[2]: array([nan, nan, nan, nan, 1., nan, nan, nan, nan, nan])

file:///C:/Users/goura/Downloads/12-Numpy.html 36/73
2/1/25, 3:40 PM 12-Numpy

Q-2 Ask user to input two numbers a, b. Write a program


to generate a random array of shape (a, b) and print the
array and avg of the array.
In [3]: #Code here
a,b = map(int, input("Enter two numbers: ").split())
x = np.random.random((a,b))
print(x)
print(x.mean())

[[0.95451402 0.82470381 0.18199219 0.92467268]


[0.1018292 0.1019591 0.83413608 0.25241595]
[0.09905596 0.46841974 0.16301038 0.0383276 ]
[0.62680046 0.05426302 0.19655785 0.53635247]
[0.60150005 0.67929756 0.15192349 0.61643755]]
0.4204084564672089

Q-3 Write a function to create a 2d array with 1 on the border and 0


inside. Take 2-D array shape as (a,b) as parameter to function.
Eg.-

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

In [4]: #Code here


def borderArray(a,b):
x = np.ones((a,b))
x[1:-1, 1:-1] = 0 # Except the border, changing all other elements to 0
return x
borderArray(4,5)

Out[4]: array([[1., 1., 1., 1., 1.],


[1., 0., 0., 0., 1.],
[1., 0., 0., 0., 1.],
[1., 1., 1., 1., 1.]])

Q-4 Create a vector of size 10 with values ranging from 0 to


1, both excluded.
In [5]: #Code here
np.linspace(0, 1, 12)[1:-1]

Out[5]: array([0.09090909, 0.18181818, 0.27272727, 0.36363636, 0.45454545,


0.54545455, 0.63636364, 0.72727273, 0.81818182, 0.90909091])

Q-5 Can you create a identity mattrix of shape (3,4). If yes


write code for it.
In [6]: #Code here
# Identity matricx is a square mattrix, means no of rows and columns will always
# Here shape given 3,4 so identuty matrix not possible.

file:///C:/Users/goura/Downloads/12-Numpy.html 37/73
2/1/25, 3:40 PM 12-Numpy

#Identy matrix of size 3-- 3X3


np.eye(3)

#Identy matrix of size 4-- 4X4


np.identity(4)

# eye and identity are same.

Out[6]: array([[1., 0., 0., 0.],


[0., 1., 0., 0.],
[0., 0., 1., 0.],
[0., 0., 0., 1.]])

Q-6: Create a 5x5 matrix with row values ranging from 0


to 4.
In [7]: #Code here
z = np.zeros((5,5))
z+= np.arange(5)
z

Out[7]: array([[0., 1., 2., 3., 4.],


[0., 1., 2., 3., 4.],
[0., 1., 2., 3., 4.],
[0., 1., 2., 3., 4.],
[0., 1., 2., 3., 4.]])

Q-7: Consider a random integer (in range 1 to 100) vector


with shape (10,2) representing coordinates, and
coordinates of a point as array is given. Create an array of
distance of each point in the random vectros from the given
point. Distance array should be interger type.
point = np.array([2,3])

In [8]: #code here


a = np.random.randint(1, 100, (10, 2))
p = np.array([2,3])
np.sqrt(np.sum((a-p)**2, axis=1)).astype(int)

Out[8]: array([ 71, 123, 104, 60, 77, 112, 72, 24, 57, 50])

Q-8: Consider a (6,7,8) shape array, what is the index


(x,y,z) of the 100th element?
In [9]: #Code here
np.unravel_index(100, (6,7,8))

Out[9]: (1, 5, 4)

Q-9: Arrays

file:///C:/Users/goura/Downloads/12-Numpy.html 38/73
2/1/25, 3:40 PM 12-Numpy

You are given a space separated list of numbers. Your task is to print a reversed NumPy
array with the element type float.

Input Format:

A single line of input containing space separated numbers.

Output Format:

Print the reverse NumPy array with type float.

Example 1:

Input:

1 2 3 4 -8 -10
Output:

[-10. -8. 4. 3. 2. 1.]

In [12]: #Code here


a = input().strip().split()
np.array(a[::-1], dtype=np.float32)

Out[12]: array([-9., -8., 5., 4., 3., 2., 1.], dtype=float32)

Q-10: Elements count


Count the number of elements of a numpy array.

Example 1:

Input:

np.array([])
Output:

elements_count : 0
Example 2:

Input:

np.array([1, 2])
Output:

elements_count : 2

In [14]: #Code here


a = np.array([])
a = np.array([1, 2])
a = np.zeros((2,3))
a.size

Out[14]: 6

file:///C:/Users/goura/Downloads/12-Numpy.html 39/73
2/1/25, 3:40 PM 12-Numpy

Q-11: Softmax function


Create a Python function to calculate the Softmax of the given numpy 1D array. The
function only accepts the numpy 1D array, otherwise raise error.

zi
e

σ(z )i =
K zj
∑ e
j=i

Example 1:

Input:

[86.03331084 37.7285648 48.64908087 87.16563062 38.40852563


37.20006318]
Output:

[2.43733249e-01, 2.56112115e-22, 1.41628284e-17, 7.56266751e-01,


5.05514197e-22, 1.50974911e-22]
Example 2:

Input:

[33.17344305 45.61961654 82.05405781 80.9647098 68.82830233


91.52064278]
Output:

[4.57181035e-26, 1.16249923e-20, 7.73872596e-05, 2.60358426e-05,


1.39571531e-10, 9.99896577e-01]

In [15]: #Code here


def softmax(arr):
if type(arr) != np.ndarray:
raise TypeError("Requires Numpy Array")
elif arr.ndim > 1:
raise TypeError("Requires 1D Array")
s = np.sum(np.exp(arr))
return np.exp(arr)/s
softmax(np.array([86.03331084, 37.7285648, 48.64908087, 87.16563062,
38.40852563, 37.20006318]))

Out[15]: array([2.43733248e-01, 2.56112114e-22, 1.41628283e-17, 7.56266752e-01,


5.05514197e-22, 1.50974911e-22])

Q-12: Vertical stack


Write a python function that accepts infinite number of numpy arrays and do the vertical
stack to them. Then return that new array as result. The function only accepts the numpy
array, otherwise raise error.

Example 1:

Input:

file:///C:/Users/goura/Downloads/12-Numpy.html 40/73
2/1/25, 3:40 PM 12-Numpy

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

b= [[1 1 1 1 1]
[1 1 1 1 1]]
Output:

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

Input:

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

b= [[1 1 1 1 1]
[1 1 1 1 1]]

c= [[0.10117373 0.1677244 0.73764059 0.83166097 0.48985695]


[0.44581567 0.13502419 0.55692335 0.16479622 0.61193593]]
Output:

[[0. 1. 2. 3. 4. ]
[5. 6. 7. 8. 9. ]
[1. 1. 1. 1. 1. ]
[1. 1. 1. 1. 1. ]
[0.10117373 0.1677244 0.73764059 0.83166097 0.48985695]
[0.44581567 0.13502419 0.55692335 0.16479622 0.61193593]]

In [16]: #Coder here


def vertical_stack(*args):
for i in args:
if type(i) != np.ndarray:
raise TypeError("Requires Numpy Array")
return np.vstack(args)

a = np.arange(10).reshape(2, -1)
print("a=",a)
b = np.repeat(1, 10).reshape(2, -1)
print("b=",b)
print(vertical_stack(a,b))
c = np.random.random((2,5))
print("c=", c)
vertical_stack(a,b,c)

file:///C:/Users/goura/Downloads/12-Numpy.html 41/73
2/1/25, 3:40 PM 12-Numpy

a= [[0 1 2 3 4]
[5 6 7 8 9]]
b= [[1 1 1 1 1]
[1 1 1 1 1]]
[[0 1 2 3 4]
[5 6 7 8 9]
[1 1 1 1 1]
[1 1 1 1 1]]
c= [[4.76733610e-04 3.84412246e-01 3.85767503e-01 1.18959841e-01
2.27924922e-01]
[6.28995410e-01 7.05174070e-01 6.21996823e-01 8.07290146e-01
6.32486280e-02]]
Out[16]: array([[0.00000000e+00, 1.00000000e+00, 2.00000000e+00, 3.00000000e+00,
4.00000000e+00],
[5.00000000e+00, 6.00000000e+00, 7.00000000e+00, 8.00000000e+00,
9.00000000e+00],
[1.00000000e+00, 1.00000000e+00, 1.00000000e+00, 1.00000000e+00,
1.00000000e+00],
[1.00000000e+00, 1.00000000e+00, 1.00000000e+00, 1.00000000e+00,
1.00000000e+00],
[4.76733610e-04, 3.84412246e-01, 3.85767503e-01, 1.18959841e-01,
2.27924922e-01],
[6.28995410e-01, 7.05174070e-01, 6.21996823e-01, 8.07290146e-01,
6.32486280e-02]])

Q-13: Dates
Create a python function named date_array that accepts two dates as string format and
returns a numpy array of dates between those 2 dates. The function only accept 2 strings,
otherwise raise error. The date format should be like this only: 2022-12-6 . The end
date should be included and for simplicity, choose dates from a same year.

Example 1:

Input:

date_array(start = '2020-09-15', end = '2020-09-25')


Output:

['2020-09-15', '2020-09-16', '2020-09-17', '2020-09-18',


'2020-09-19', '2020-09-20', '2020-09-21', '2020-09-22',
'2020-09-23', '2020-09-24', '2020-09-25']
Example 2:

Input:

date_array(start = '2022-12-01', end = '2022-12-06')


Output:

['2022-12-01', '2022-12-02', '2022-12-03', '2022-12-04', '2022-12-05',


'2022-12-06']
Example 3:

Input:

date_array(start = '2020-11-25', end = '2020-11-30')

file:///C:/Users/goura/Downloads/12-Numpy.html 42/73
2/1/25, 3:40 PM 12-Numpy

Output:

['2020-11-25', '2020-11-26', '2020-11-27', '2020-11-28',


'2020-11-29', '2020-11-30']

In [17]: #Code here

def date_array(start: str, end: str):


if type(start) != str or type(end) != str:
raise TypeError

total_days_of_month = {"01": 31, "02": 28, "03": 31, "04":30, "05": 31, "06"

end = end.split("-")
end_last = int(end[-1]) + 1

# If the next day of end falls in the next month, account for that
if total_days_of_month[end[-2]] < end_last:
days_diff = end_last - total_days_of_month[end[-2]]
end[-1] = f'0{days_diff}' if days_diff< 10 else f'{days_diff}'
next_month = int(end[-2]) + 1
end[-2] = f'0{next_month}' if next_month< 10 else f'{next_month}'
else:
end[-1] = f'0{end_last}' if end_last < 10 else f'{end_last}'
end = "-".join(end)
# Use arange() to generate all dates between start and end
return np.arange(start, end, dtype="datetime64[D]")
date_array(start = '2020-11-25', end = '2020-11-30')

Out[17]: array(['2020-11-25', '2020-11-26', '2020-11-27', '2020-11-28',


'2020-11-29', '2020-11-30'], dtype='datetime64[D]')

Q-14: Subtract the mean of each row from a matrix.

In [18]: #code here


x = np.random.random((5,4))
x - x.mean(axis = 1, keepdims = True)

Out[18]: array([[ 0.14082121, 0.16549577, -0.19648327, -0.10983371],


[-0.01073746, -0.19130834, 0.02839127, 0.17365453],
[-0.26280214, -0.08599194, 0.14665937, 0.20213471],
[ 0.38411362, 0.25075062, -0.24663013, -0.38823412],
[-0.3727299 , 0.16482396, 0.10014632, 0.10775962]])

Q-15: Swap column-1 of array with column-2 in the array.

In [19]: #Code here


a = np.arange(9).reshape(3,3)
a[:, [0, 2, 1]]

Out[19]: array([[0, 2, 1],


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

Q-16: Replace odd elements in arrays with -1.

file:///C:/Users/goura/Downloads/12-Numpy.html 43/73
2/1/25, 3:40 PM 12-Numpy

In [20]: #Code here


a = np.arange(10)
a[a%2 == 1] = -1
a

Out[20]: array([ 0, -1, 2, -1, 4, -1, 6, -1, 8, -1])

Q-17: Given two arrays of same shape make an array of


max out of two arrays. (Numpy way)
a=np.array([6,3,1,5,8])
b=np.array([3,2,1,7,2])

Result-> [6 3 1 7 8]

In [21]: #Code here


a=np.array([6,3,1,5,8])
b=np.array([3,2,1,7,2])

a[b>a] = b[a<b]
a

Out[21]: array([6, 3, 1, 7, 8])

Q-18 Answer below asked questions on given array:


1. Fetch Every alternate column of the array
2. Normalise the given array

https://en.wikipedia.org/wiki/Normalization_(statistics)

There are different form of normalisation for this question use below formula.

X − Xmin
Xnormalized =
Xmax − Xmin

arr1=np.random.randint(low=1, high=10000, size=40).reshape(8,5)

In [22]: # Given
arr1=np.random.randint(low=1, high=10000, size=40).reshape(8,5)
arr1

Out[22]: array([[2841, 9057, 3298, 9395, 6620],


[6470, 4184, 6478, 8237, 1692],
[5132, 2582, 2542, 6830, 2109],
[9250, 2691, 4044, 3603, 9119],
[2067, 3233, 3794, 8757, 8153],
[3290, 680, 2714, 7729, 6290],
[5059, 8168, 9172, 422, 6223],
[7115, 7907, 3459, 6519, 7577]])

In [23]: #Code here


#1
arr1[:, ::2]

file:///C:/Users/goura/Downloads/12-Numpy.html 44/73
2/1/25, 3:40 PM 12-Numpy

Out[23]: array([[2841, 3298, 6620],


[6470, 6478, 1692],
[5132, 2542, 2109],
[9250, 4044, 9119],
[2067, 3794, 8153],
[3290, 2714, 6290],
[5059, 9172, 6223],
[7115, 3459, 7577]])

In [24]: (arr1 - arr1.min())/(arr1.max() - arr1.min())

Out[24]: array([[0.26958654, 0.96233144, 0.32051711, 1. , 0.69073888],


[0.67402207, 0.41925777, 0.67491363, 0.87094617, 0.14153572],
[0.52490806, 0.24072217, 0.23626435, 0.71414243, 0.18800847],
[0.98384041, 0.25286972, 0.40365541, 0.35450797, 0.96924106],
[0.18332776, 0.31327315, 0.37579405, 0.9288978 , 0.86158475],
[0.31962554, 0.02875293, 0.25543297, 0.81433188, 0.65396189],
[0.51677254, 0.86325644, 0.97514767, 0. , 0.64649504],
[0.74590438, 0.83416917, 0.33845982, 0.67948289, 0.79739218]])

Q-19: Write a function which will accept 2 arguments.


First: A 1D numpy array arr

Second: An integer n {Please make sure n<=len(arr)}

Output: The output should be the nth largest item out of the array

# Example1 : arr=(12,34,40,7,1,0) and n=3, the output should be


12
# Example2 : arr=(12,34,40,7,1,0) and n=1, the output should be
40

In [25]: #Code here


def nthmax(arr, n):
if n>len(arr):
raise IndexError("n is way out of limit")
arr.sort()
return arr[-n]
nthmax(np.array([12,34,40,7,1,0]),2)

Out[25]: 34

Q-20: Create the following pattern without hardcoding.


Use only numpy functions and the below input array a.
# Input: a = np.array([1,2,3])
# Output: array([1, 1, 1, 2, 2, 2, 3, 3, 3, 1, 2, 3, 1, 2, 3, 1,
2, 3])

In [27]: #code here


a = np.array([1,2,3])
np.hstack([np.repeat(a, 3), np.tile(a, 3)])

file:///C:/Users/goura/Downloads/12-Numpy.html 45/73
2/1/25, 3:40 PM 12-Numpy

Out[27]: array([1, 1, 1, 2, 2, 2, 3, 3, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3])

Q-1: Find the nearest element in the array to a given


integer.
Ex:-
a=23 and array - [10 17 24 31 38 45 52 59].
Nearest element is 24

Hint: Read about this function argmin()

In [28]: # code here


arr = np.array([10, 17, 24, 31, 38, 45, 52, 59])
a=39
arr[abs(arr - a).argmin()]

Out[28]: 38

Q-2: Replace multiples of 3 or 5 as 0 in the given array.


arr=[1 2 3 4 5 6 7 9]

result-> [1 2 0 4 0 0 7 0]

In [29]: # code here


arr=np.array([1, 2, 3, 4, 5, 6, 7, 9])
arr[(arr%3==0) | (arr%5==0)] = 0
arr

Out[29]: array([1, 2, 0, 4, 0, 0, 7, 0])

Q-3: Use Fancy Indexing.


1. Double the array elements at given indexes

arr = np.arrange(10)
indexes = [0,3,4,9]

Result -> [ 0 1 2 6 8 5 6 7 8 18]

2. Using a given array make a different array as in below example

array = [1,2,3]
result array -> [1 1 1 2 2 2 3 3 3]

Internal-repetion should be as length of the array.

Hint:

if a is an array
a = [2,4]

file:///C:/Users/goura/Downloads/12-Numpy.html 46/73
2/1/25, 3:40 PM 12-Numpy

a[[1,1,0,1]] will result in-> [4 4 2 4]

In [30]: # code here


#1
arr = np.arange(10)
indexes = [0,3,4,9]
arr[indexes] *=2
arr

Out[30]: array([ 0, 1, 2, 6, 8, 5, 6, 7, 8, 18])

In [31]: array = np.array([1,2,3])


indexes = []
for index in range(len(array)):
indexes.extend([index] * len(array))
array[indexes]

Out[31]: array([1, 1, 1, 2, 2, 2, 3, 3, 3])

Q-4: Your are given an array which is havig some nan


value. You job is to fill those nan values with most common
element in the array.
arr=np.array([[1,2,np.nan],[4,2,6],[np.nan,np.nan,5]])

In [32]: # code here


arr=np.array([[1,2,np.nan],[4,2,6],[np.nan,np.nan,5]])
d = {}
for i in arr.flatten():
if i in d:
d[i] += 1
else:
d[i] = 1

arr[np.isnan(arr)] = sorted(d.items(), key = lambda x: x[1])[-1][0]


arr

Out[32]: array([[1., 2., 2.],


[4., 2., 6.],
[2., 2., 5.]])

Q-5: Write a NumPy program


to find the missing data in a given array. Return a boolean matrix.
also try to fill those missing values with 0. For that, you can use
np.nan_to_num(a)

import numpy as np

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


[10, 12, 10, 9],
[5, np.nan, 1, np.nan]])

file:///C:/Users/goura/Downloads/12-Numpy.html 47/73
2/1/25, 3:40 PM 12-Numpy

In [33]: # code here


#1
arr = np.array([[3, 2, np.nan, 1],
[10, 12, 10, 9],
[5, np.nan, 1, np.nan]])
np.isnan(arr)

Out[33]: array([[False, False, True, False],


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

In [34]: #2
np.nan_to_num(arr)

Out[34]: array([[ 3., 2., 0., 1.],


[10., 12., 10., 9.],
[ 5., 0., 1., 0.]])

Q-6: Given two arrays, X and Y, construct the Cauchy


matrix C.
Cij =1/(xi - yj)

http://en.wikipedia.org/wiki/Cauchy_matrix

x = numpy.array([1,2,3,4]).reshape((-1, 1)
y = numpy.array([5,6,7])

In [36]: # code here


x = np.array([1,2,3,4]).reshape((-1, 1))
y = np.array([5,6,7])

1/(x-y)

Out[36]: array([[-0.25 , -0.2 , -0.16666667],


[-0.33333333, -0.25 , -0.2 ],
[-0.5 , -0.33333333, -0.25 ],
[-1. , -0.5 , -0.33333333]])

Q-7: Plot this below equation.


x −x
e − e
y =
x −x
e + e

Note: This equation is called tanh activation function. In deep learning, many times
this function is used. If you find some difference between the sigmoid function and
this tanh function, note that to your notebook.

In [37]: # code here


import matplotlib.pyplot as plt

x = np.linspace(-30, 30, 1000)


y = (np.exp(x) - np.exp(-x)) / (np.exp(x) + np.exp(-x))

file:///C:/Users/goura/Downloads/12-Numpy.html 48/73
2/1/25, 3:40 PM 12-Numpy

plt.plot(x,y)

Out[37]: [<matplotlib.lines.Line2D at 0x16743816ad0>]

Q-8: Plot the below equation.


2
y = √36 − (x − 4) + 2

The range of x should be between -2 to 10. x ∈ [−2, 10]

In [38]: # code here


x = np.linspace(-2, 10, 100)
y = np.sqrt(36 - (x-4)**2) + 2

plt.plot(x,y)

Out[38]: [<matplotlib.lines.Line2D at 0x16743c17750>]

file:///C:/Users/goura/Downloads/12-Numpy.html 49/73
2/1/25, 3:40 PM 12-Numpy

Q-9: Write a program implement Broadcasting Rule to


check if two array can be added or not.
Given tuples of shapes.

shape of a- (3,2,2)
shape of b- (2,2)

check_broadcast(a, b) -> return Boolean (True if can


broadcasted, False other wise.)

In [39]: # code here

# 4 3 3 5
# 2 5

# Align both shapes


# Loop for both shapes from behind
# If two numbers are not equal and none of the numbers are 1, return false
# return true

def check_broadcast(a,b):
a = a[::-1]
b = b[::-1]
for ai, bi in zip(a,b):
if ai != bi and ai != 1 and bi != 1:
return False
return

In [40]: check_broadcast((4,3,3,5),(2,5))

file:///C:/Users/goura/Downloads/12-Numpy.html 50/73
2/1/25, 3:40 PM 12-Numpy

Out[40]: False

Q-1: Create a random 3x4 matrix with value between 0-


100. And perform below tasks
i. Sort this matrix. np.sort()
ii. Sort this matrix based on values in 2nd column.
iii. Sort this matrix based on max value in each row.
iv. Sort based on elements value.

See examples:

arr =
[[92 90 74]
[ 6 63 93]
[15 93 96]
[70 60 48]]

i. np.sort
[[74 90 92]
[ 6 63 93]
[15 93 96]
[48 60 70]]

ii. based on 2nd column


[[70 60 48]
[ 6 63 93]
[92 90 74]
[15 93 96]]

iii. based on row max- ascending


[[15 93 96]
[ 6 63 93]
[92 90 74]
[70 60 48]]

iv. based on elements value


[[ 6 15 48]
[60 63 70]
[74 90 92]
[93 93 96]]

In [42]: # code here


arr = np.random.randint(0, 100, (4,3))
print(arr)
#1
print(np.sort(arr))
#2
print(arr[arr[:, 1].argsort()])
#3
print(np.array(sorted(arr, key = lambda x: max(x))))
#4
print(np.sort(arr, axis = None).reshape(4,3))

file:///C:/Users/goura/Downloads/12-Numpy.html 51/73
2/1/25, 3:40 PM 12-Numpy

[[86 66 10]
[30 9 54]
[35 92 93]
[22 17 30]]
[[10 66 86]
[ 9 30 54]
[35 92 93]
[17 22 30]]
[[30 9 54]
[22 17 30]
[86 66 10]
[35 92 93]]
[[22 17 30]
[30 9 54]
[86 66 10]
[35 92 93]]
[[ 9 10 17]
[22 30 30]
[35 54 66]
[86 92 93]]

Q-2: There is an array of marks of 5


students in 4 subjects. Further you are
asked to perform below task.
i. Add marks every student of an extra subject in the same
array.
ii. Add two new students marks in respective 5 subjects.(one
subject added in above task)
iii. Add extra column with sum of all subjects(5-subjects) marks
iv. Sort the array(non-ascending order) on total marks column--
one added in above task. Show top 2 rows.

Note: Change dimension of arrays during concatenation or appending if required.

Given Array-

marks = [[13, 10, 9, 33],


[63, 46, 90, 42],
[39, 76, 13, 29],
[82, 9, 29, 78],
[67, 61, 59, 36]]

extra_subject = [41, 87, 72, 36, 92]


#Two extra students record-
rec1 = [77, 83, 98, 95, 89]
rec2 = [92, 71, 52, 61, 53]

In [43]: # code here


marks = np.array([[13, 10, 9, 33],
[63, 46, 90, 42],
[39, 76, 13, 29],

file:///C:/Users/goura/Downloads/12-Numpy.html 52/73
2/1/25, 3:40 PM 12-Numpy

[82, 9, 29, 78],


[67, 61, 59, 36]])
extra_subject = np.array([41, 87, 72, 36, 92]).reshape(-1, 1)
marks = np.concatenate([marks, extra_subject], axis = 1)
#2
rec1 = np.array([77, 83, 98, 95, 89]).reshape(1, -1)
rec2 = np.array( [92, 71, 52, 61, 53]).reshape(1, -1)
marks = np.concatenate([marks, rec1, rec2], axis = 0)
#3
sum_of_stud = marks.sum(axis = 1, keepdims=True)
marks = np.concatenate([marks, sum_of_stud], axis = 1)
#4
print(np.array(sorted(marks, key = lambda x: x[-1], reverse=True)))

[[ 77 83 98 95 89 442]
[ 92 71 52 61 53 329]
[ 63 46 90 42 87 328]
[ 67 61 59 36 92 315]
[ 82 9 29 78 36 234]
[ 39 76 13 29 72 229]
[ 13 10 9 33 41 106]]

Q-3: Find unique arrays from a 2D array column wise and


row wise.
arr = np.array([[1,2,3,3,1,1],
[0,9,1,2,8,8],
[1,2,3,8,8,8],
[1,2,3,3,1,1]])

Expected Result-

Row Wise
[[0 9 1 2 8 8]
[1 2 3 3 1 1]
[1 2 3 8 8 8]]

Col Wise
[[1 1 2 3 3]
[0 8 9 1 2]
[1 8 2 3 8]
[1 1 2 3 3]]

In [44]: # code here


arr = np.array([[1,2,3,3,1,1],
[0,9,1,2,8,8],
[1,2,3,8,8,8],
[1,2,3,3,1,1]])
#1
print(np.unique(arr, axis = 0))
#2
print(np.unique(arr, axis = 1))

file:///C:/Users/goura/Downloads/12-Numpy.html 53/73
2/1/25, 3:40 PM 12-Numpy

[[0 9 1 2 8 8]
[1 2 3 3 1 1]
[1 2 3 8 8 8]]
[[1 1 2 3 3]
[0 8 9 1 2]
[1 8 2 3 8]
[1 1 2 3 3]]

Q-4: Flip given 2-D array along both axes at the same
time.
In [45]: # code here
arr = np.array([[1,2,3,3,1,1],
[0,9,1,2,8,8],
[1,2,3,8,8,8],
[1,2,3,3,1,1],
[0,6,1,2,11,7],
[10,19,14,-2,8,-1]])
np.flip(arr, axis = [0, 1])

Out[45]: array([[-1, 8, -2, 14, 19, 10],


[ 7, 11, 2, 1, 6, 0],
[ 1, 1, 3, 3, 2, 1],
[ 8, 8, 8, 3, 2, 1],
[ 8, 8, 2, 1, 9, 0],
[ 1, 1, 3, 3, 2, 1]])

Q-5: Get row numbers of NumPy array having element


larger than X.
arr = [[1,2,3,4,5],
[10,-3,30,4,5],
[3,2,5,-4,5],
[9,7,3,6,5]]

X = 6

In [46]: # code here


arr = np.array([[1,2,3,4,5],
[10,-3,30,4,5],
[3,2,5,-4,5],
[9,7,3,6,5]] )
X = 6

np.where(np.any(arr > X, axis = 1))

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

Q-6: How to convert an array of arrays into a flat 1d array?

In [47]: # These arrays are given.


arr1 = np.arange(3)
arr2 = np.arange(3,7)
arr3 = np.arange(7,10)

file:///C:/Users/goura/Downloads/12-Numpy.html 54/73
2/1/25, 3:40 PM 12-Numpy

In [48]: # code here


np.concatenate([arr1, arr2, arr3])

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

Q-7: You are given a array. You have to find the minimum
and maximum array element and remove that from the
array.
import numpy as np

np.random.seed(400)
arr = np.random.randint(100, 1000, 200).reshape((1, 200))

In [49]: # code here


np.random.seed(400)
arr = np.random.randint(100, 1000, 200).reshape((1, 200))
print(arr)
max_element = arr.argmax()
min_element = arr.argmin()
print(arr.max(), arr.min())
arr = np.delete(arr, max_element, axis = 1)
arr = np.delete(arr, min_element, axis = 1)
print(arr.max(), arr.min())

[[448 563 418 240 507 362 345 236 719 291 298 639 458 387 262 613 267 882
181 425 790 635 889 818 872 967 277 470 336 920 917 295 557 830 506 385
353 975 592 997 137 340 222 215 472 459 617 649 935 956 914 932 645 952
921 490 527 972 278 307 840 958 246 449 251 957 103 627 920 824 356 825
173 323 372 960 710 464 244 782 763 635 436 774 171 469 178 458 624 211
771 270 308 231 952 514 699 702 433 900 373 318 998 265 503 320 230 324
922 967 620 743 527 117 566 804 123 946 587 227 853 757 944 328 855 930
325 729 426 514 296 879 575 936 705 209 191 743 510 513 628 559 658 528
395 525 922 136 496 225 895 975 263 908 420 711 800 976 786 235 930 859
618 226 695 460 218 483 490 803 621 453 193 607 677 637 728 724 534 748
291 194 761 875 687 569 228 482 781 554 654 739 885 197 266 228 892 207
883 588]]
998 103
997 117

Q-8: You are given an arrays. You have to limit this array's
elements between 100 to 200. arr ∈ [100, 200]. So replace
those values accordingly with the minimum and maximum
value. Then sort the array and perform the cumulative sum
of that array.
In [50]: # code here
arr = np.random.randint(0, 2000, 500)
np.cumsum(np.sort(np.clip(arr, 100, 200)))

file:///C:/Users/goura/Downloads/12-Numpy.html 55/73
2/1/25, 3:40 PM 12-Numpy

Out[50]: array([ 100, 200, 300, 400, 500, 600, 700, 800, 900,
1000, 1100, 1200, 1300, 1400, 1500, 1600, 1700, 1800,
1900, 2000, 2100, 2224, 2350, 2478, 2614, 2751, 2892,
3035, 3180, 3330, 3482, 3640, 3803, 3966, 4142, 4321,
4505, 4693, 4883, 5082, 5282, 5482, 5682, 5882, 6082,
6282, 6482, 6682, 6882, 7082, 7282, 7482, 7682, 7882,
8082, 8282, 8482, 8682, 8882, 9082, 9282, 9482, 9682,
9882, 10082, 10282, 10482, 10682, 10882, 11082, 11282, 11482,
11682, 11882, 12082, 12282, 12482, 12682, 12882, 13082, 13282,
13482, 13682, 13882, 14082, 14282, 14482, 14682, 14882, 15082,
15282, 15482, 15682, 15882, 16082, 16282, 16482, 16682, 16882,
17082, 17282, 17482, 17682, 17882, 18082, 18282, 18482, 18682,
18882, 19082, 19282, 19482, 19682, 19882, 20082, 20282, 20482,
20682, 20882, 21082, 21282, 21482, 21682, 21882, 22082, 22282,
22482, 22682, 22882, 23082, 23282, 23482, 23682, 23882, 24082,
24282, 24482, 24682, 24882, 25082, 25282, 25482, 25682, 25882,
26082, 26282, 26482, 26682, 26882, 27082, 27282, 27482, 27682,
27882, 28082, 28282, 28482, 28682, 28882, 29082, 29282, 29482,
29682, 29882, 30082, 30282, 30482, 30682, 30882, 31082, 31282,
31482, 31682, 31882, 32082, 32282, 32482, 32682, 32882, 33082,
33282, 33482, 33682, 33882, 34082, 34282, 34482, 34682, 34882,
35082, 35282, 35482, 35682, 35882, 36082, 36282, 36482, 36682,
36882, 37082, 37282, 37482, 37682, 37882, 38082, 38282, 38482,
38682, 38882, 39082, 39282, 39482, 39682, 39882, 40082, 40282,
40482, 40682, 40882, 41082, 41282, 41482, 41682, 41882, 42082,
42282, 42482, 42682, 42882, 43082, 43282, 43482, 43682, 43882,
44082, 44282, 44482, 44682, 44882, 45082, 45282, 45482, 45682,
45882, 46082, 46282, 46482, 46682, 46882, 47082, 47282, 47482,
47682, 47882, 48082, 48282, 48482, 48682, 48882, 49082, 49282,
49482, 49682, 49882, 50082, 50282, 50482, 50682, 50882, 51082,
51282, 51482, 51682, 51882, 52082, 52282, 52482, 52682, 52882,
53082, 53282, 53482, 53682, 53882, 54082, 54282, 54482, 54682,
54882, 55082, 55282, 55482, 55682, 55882, 56082, 56282, 56482,
56682, 56882, 57082, 57282, 57482, 57682, 57882, 58082, 58282,
58482, 58682, 58882, 59082, 59282, 59482, 59682, 59882, 60082,
60282, 60482, 60682, 60882, 61082, 61282, 61482, 61682, 61882,
62082, 62282, 62482, 62682, 62882, 63082, 63282, 63482, 63682,
63882, 64082, 64282, 64482, 64682, 64882, 65082, 65282, 65482,
65682, 65882, 66082, 66282, 66482, 66682, 66882, 67082, 67282,
67482, 67682, 67882, 68082, 68282, 68482, 68682, 68882, 69082,
69282, 69482, 69682, 69882, 70082, 70282, 70482, 70682, 70882,
71082, 71282, 71482, 71682, 71882, 72082, 72282, 72482, 72682,
72882, 73082, 73282, 73482, 73682, 73882, 74082, 74282, 74482,
74682, 74882, 75082, 75282, 75482, 75682, 75882, 76082, 76282,
76482, 76682, 76882, 77082, 77282, 77482, 77682, 77882, 78082,
78282, 78482, 78682, 78882, 79082, 79282, 79482, 79682, 79882,
80082, 80282, 80482, 80682, 80882, 81082, 81282, 81482, 81682,
81882, 82082, 82282, 82482, 82682, 82882, 83082, 83282, 83482,
83682, 83882, 84082, 84282, 84482, 84682, 84882, 85082, 85282,
85482, 85682, 85882, 86082, 86282, 86482, 86682, 86882, 87082,
87282, 87482, 87682, 87882, 88082, 88282, 88482, 88682, 88882,
89082, 89282, 89482, 89682, 89882, 90082, 90282, 90482, 90682,
90882, 91082, 91282, 91482, 91682, 91882, 92082, 92282, 92482,
92682, 92882, 93082, 93282, 93482, 93682, 93882, 94082, 94282,
94482, 94682, 94882, 95082, 95282, 95482, 95682, 95882, 96082,
96282, 96482, 96682, 96882, 97082])

file:///C:/Users/goura/Downloads/12-Numpy.html 56/73
2/1/25, 3:40 PM 12-Numpy

Q-9: You are given a array (arr ∈ [0, 1]). First you have
round off the elements upto 3 decimal places and compare
that
0th percentile == minimum value of the array
100th percentile == maximum value of the array
also find the difference betwen 51th percenile and 50th percentile values

In [51]: # code here


arr = np.random.random(100)
arr = np.around(arr, decimals = 3)

print("0th percentile == minimum value of the array: ", (np.percentile(arr, 0) =


print("100th percentile == maximum value of the array: ", (np.percentile(arr, 10
print("difference betwen 51th percenile and 50th percentile values: ", (np.perce

0th percentile == minimum value of the array: True


100th percentile == maximum value of the array: True
difference betwen 51th percenile and 50th percentile values: 0.01285000000000002
8

Interview Questions
In [52]: import numpy as np
import warnings
warnings.filterwarnings('ignore')

In [53]: # plotting 3D graphs


# meshgrids
a = np.linspace(-10,9,20)
b = np.linspace(-10,9,20)
b

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

In [54]: xx,yy = np.meshgrid(a,b)


yy

file:///C:/Users/goura/Downloads/12-Numpy.html 57/73
2/1/25, 3:40 PM 12-Numpy

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

In [55]: import matplotlib.pyplot as plt


plt.scatter(xx,yy)

Out[55]: <matplotlib.collections.PathCollection at 0x167436dab90>

file:///C:/Users/goura/Downloads/12-Numpy.html 58/73
2/1/25, 3:40 PM 12-Numpy

In [56]: def func(x,y):


return 3*np.log(x) + 2*y

zz = func(xx,yy)
zz

file:///C:/Users/goura/Downloads/12-Numpy.html 59/73
2/1/25, 3:40 PM 12-Numpy

Out[56]: array([[ nan, nan, nan, nan,


nan, nan, nan, nan,
nan, nan, -inf, -20. ,
-17.92055846, -16.70416313, -15.84111692, -15.17168626,
-14.62472159, -14.16226955, -13.76167537, -13.40832627],
[ nan, nan, nan, nan,
nan, nan, nan, nan,
nan, nan, -inf, -18. ,
-15.92055846, -14.70416313, -13.84111692, -13.17168626,
-12.62472159, -12.16226955, -11.76167537, -11.40832627],
[ nan, nan, nan, nan,
nan, nan, nan, nan,
nan, nan, -inf, -16. ,
-13.92055846, -12.70416313, -11.84111692, -11.17168626,
-10.62472159, -10.16226955, -9.76167537, -9.40832627],
[ nan, nan, nan, nan,
nan, nan, nan, nan,
nan, nan, -inf, -14. ,
-11.92055846, -10.70416313, -9.84111692, -9.17168626,
-8.62472159, -8.16226955, -7.76167537, -7.40832627],
[ nan, nan, nan, nan,
nan, nan, nan, nan,
nan, nan, -inf, -12. ,
-9.92055846, -8.70416313, -7.84111692, -7.17168626,
-6.62472159, -6.16226955, -5.76167537, -5.40832627],
[ nan, nan, nan, nan,
nan, nan, nan, nan,
nan, nan, -inf, -10. ,
-7.92055846, -6.70416313, -5.84111692, -5.17168626,
-4.62472159, -4.16226955, -3.76167537, -3.40832627],
[ nan, nan, nan, nan,
nan, nan, nan, nan,
nan, nan, -inf, -8. ,
-5.92055846, -4.70416313, -3.84111692, -3.17168626,
-2.62472159, -2.16226955, -1.76167537, -1.40832627],
[ nan, nan, nan, nan,
nan, nan, nan, nan,
nan, nan, -inf, -6. ,
-3.92055846, -2.70416313, -1.84111692, -1.17168626,
-0.62472159, -0.16226955, 0.23832463, 0.59167373],
[ nan, nan, nan, nan,
nan, nan, nan, nan,
nan, nan, -inf, -4. ,
-1.92055846, -0.70416313, 0.15888308, 0.82831374,
1.37527841, 1.83773045, 2.23832463, 2.59167373],
[ nan, nan, nan, nan,
nan, nan, nan, nan,
nan, nan, -inf, -2. ,
0.07944154, 1.29583687, 2.15888308, 2.82831374,
3.37527841, 3.83773045, 4.23832463, 4.59167373],
[ nan, nan, nan, nan,
nan, nan, nan, nan,
nan, nan, -inf, 0. ,
2.07944154, 3.29583687, 4.15888308, 4.82831374,
5.37527841, 5.83773045, 6.23832463, 6.59167373],
[ nan, nan, nan, nan,
nan, nan, nan, nan,
nan, nan, -inf, 2. ,
4.07944154, 5.29583687, 6.15888308, 6.82831374,
7.37527841, 7.83773045, 8.23832463, 8.59167373],

file:///C:/Users/goura/Downloads/12-Numpy.html 60/73
2/1/25, 3:40 PM 12-Numpy

[ nan, nan, nan, nan,


nan, nan, nan, nan,
nan, nan, -inf, 4. ,
6.07944154, 7.29583687, 8.15888308, 8.82831374,
9.37527841, 9.83773045, 10.23832463, 10.59167373],
[ nan, nan, nan, nan,
nan, nan, nan, nan,
nan, nan, -inf, 6. ,
8.07944154, 9.29583687, 10.15888308, 10.82831374,
11.37527841, 11.83773045, 12.23832463, 12.59167373],
[ nan, nan, nan, nan,
nan, nan, nan, nan,
nan, nan, -inf, 8. ,
10.07944154, 11.29583687, 12.15888308, 12.82831374,
13.37527841, 13.83773045, 14.23832463, 14.59167373],
[ nan, nan, nan, nan,
nan, nan, nan, nan,
nan, nan, -inf, 10. ,
12.07944154, 13.29583687, 14.15888308, 14.82831374,
15.37527841, 15.83773045, 16.23832463, 16.59167373],
[ nan, nan, nan, nan,
nan, nan, nan, nan,
nan, nan, -inf, 12. ,
14.07944154, 15.29583687, 16.15888308, 16.82831374,
17.37527841, 17.83773045, 18.23832463, 18.59167373],
[ nan, nan, nan, nan,
nan, nan, nan, nan,
nan, nan, -inf, 14. ,
16.07944154, 17.29583687, 18.15888308, 18.82831374,
19.37527841, 19.83773045, 20.23832463, 20.59167373],
[ nan, nan, nan, nan,
nan, nan, nan, nan,
nan, nan, -inf, 16. ,
18.07944154, 19.29583687, 20.15888308, 20.82831374,
21.37527841, 21.83773045, 22.23832463, 22.59167373],
[ nan, nan, nan, nan,
nan, nan, nan, nan,
nan, nan, -inf, 18. ,
20.07944154, 21.29583687, 22.15888308, 22.82831374,
23.37527841, 23.83773045, 24.23832463, 24.59167373]])

In [57]: import plotly.express as px


import plotly.graph_objects as go

fig = px.scatter_3d()

fig.add_trace(go.Surface(x=xx,y=yy,z=zz))

fig.show()

file:///C:/Users/goura/Downloads/12-Numpy.html 61/73
2/1/25, 3:40 PM 12-Numpy

In [58]: np.random.random((2,3,2))

Out[58]: array([[[0.64044185, 0.32749297],


[0.00564548, 0.75619514],
[0.06102714, 0.30933001]],

[[0.23529366, 0.61801493],
[0.74654678, 0.48035522],
[0.35647929, 0.80451855]]])

In [59]: np.random.seed(0)
np.random.randint(1,100,12).reshape(3,4)

Out[59]: array([[45, 48, 65, 68],


[68, 10, 84, 22],
[37, 88, 71, 89]])

In [60]: np.random.seed(0)
np.random.randint(1,100,12).reshape(3,4)

Out[60]: array([[45, 48, 65, 68],


[68, 10, 84, 22],
[37, 88, 71, 89]])

In [61]: np.random.seed(0)
np.random.randint(1,100,12).reshape(3,4)

file:///C:/Users/goura/Downloads/12-Numpy.html 62/73
2/1/25, 3:40 PM 12-Numpy

Out[61]: array([[45, 48, 65, 68],


[68, 10, 84, 22],
[37, 88, 71, 89]])

In [62]: a = np.array([12,41,33,67,89,100])
print(a)

[ 12 41 33 67 89 100]

In [63]: np.random.shuffle(a)

In [64]: a

Out[64]: array([ 67, 100, 41, 33, 89, 12])

In [65]: np.random.choice(a,3,replace=False)

Out[65]: array([12, 41, 33])

In [66]: # working with images


import cv2

In [67]: # read the image


img = cv2.imread('pics_copy.jpg')

In [68]: # show array -> shape


img.shape

Out[68]: (2001, 3000, 3)

In [69]: # show image


plt.imshow(np.flip(img,axis=1))

Out[69]: <matplotlib.image.AxesImage at 0x1674878a110>

file:///C:/Users/goura/Downloads/12-Numpy.html 63/73
2/1/25, 3:40 PM 12-Numpy

In [70]: # flip
a = np.arange(6).reshape(2,3)
a

Out[70]: array([[0, 1, 2],


[3, 4, 5]])

In [71]: np.flip(a)

Out[71]: array([[5, 4, 3],


[2, 1, 0]])

In [72]: # clip -> fade


plt.imshow(np.clip(img,0,100))

Out[72]: <matplotlib.image.AxesImage at 0x16742d5ffd0>

In [73]: # negative
plt.imshow(255 - img)

Out[73]: <matplotlib.image.AxesImage at 0x1674bf667d0>

file:///C:/Users/goura/Downloads/12-Numpy.html 64/73
2/1/25, 3:40 PM 12-Numpy

In [74]: # trim
plt.imshow(img[100:900,50:900,:])

Out[74]: <matplotlib.image.AxesImage at 0x1674bfda950>

In [75]: # plot histogram


plt.hist(img.flatten(),bins=255)

file:///C:/Users/goura/Downloads/12-Numpy.html 65/73
2/1/25, 3:40 PM 12-Numpy

Out[75]: (array([7.21623e+05, 1.06335e+05, 8.31260e+04, 7.39150e+04, 6.95460e+04,


7.81290e+04, 7.21340e+04, 8.11400e+04, 7.37120e+04, 7.93300e+04,
8.35860e+04, 8.64120e+04, 8.89140e+04, 9.15320e+04, 9.23350e+04,
1.03795e+05, 1.05547e+05, 9.99540e+04, 1.04781e+05, 9.27150e+04,
8.84400e+04, 8.44970e+04, 8.45040e+04, 8.56800e+04, 8.57750e+04,
8.36560e+04, 8.40600e+04, 8.77670e+04, 8.73840e+04, 8.73970e+04,
8.39520e+04, 8.15490e+04, 8.07080e+04, 8.22430e+04, 7.90790e+04,
8.34470e+04, 8.92640e+04, 9.17140e+04, 9.38880e+04, 9.62560e+04,
9.11500e+04, 8.99290e+04, 8.85810e+04, 8.59850e+04, 8.73360e+04,
9.69640e+04, 9.50320e+04, 9.50820e+04, 9.94020e+04, 9.53100e+04,
9.56630e+04, 9.51870e+04, 9.57910e+04, 8.93590e+04, 9.00600e+04,
8.90150e+04, 8.90470e+04, 8.66200e+04, 8.74180e+04, 8.38930e+04,
8.38750e+04, 8.27440e+04, 8.60360e+04, 8.58680e+04, 8.95140e+04,
9.00930e+04, 9.20030e+04, 9.19070e+04, 9.05150e+04, 8.73090e+04,
8.71080e+04, 8.44750e+04, 8.55980e+04, 8.69640e+04, 9.00090e+04,
8.86280e+04, 9.04280e+04, 8.92300e+04, 9.03580e+04, 9.11380e+04,
9.19050e+04, 9.34730e+04, 9.17600e+04, 9.52390e+04, 9.90820e+04,
1.04573e+05, 1.07339e+05, 1.05785e+05, 1.03877e+05, 9.55490e+04,
9.45580e+04, 9.86780e+04, 9.37060e+04, 9.23530e+04, 9.01700e+04,
8.83570e+04, 8.70860e+04, 8.59670e+04, 8.27280e+04, 8.21070e+04,
7.93120e+04, 8.02900e+04, 8.02700e+04, 7.96460e+04, 8.00120e+04,
7.93520e+04, 7.95750e+04, 7.69350e+04, 7.53510e+04, 7.53200e+04,
7.31490e+04, 7.18640e+04, 7.06760e+04, 7.08030e+04, 7.22020e+04,
7.57130e+04, 7.65450e+04, 7.64920e+04, 7.73940e+04, 7.86010e+04,
7.87080e+04, 8.05870e+04, 7.97300e+04, 8.05950e+04, 8.03200e+04,
8.01710e+04, 7.88450e+04, 7.74630e+04, 7.84810e+04, 7.79870e+04,
7.66840e+04, 7.68130e+04, 7.76880e+04, 7.74430e+04, 7.64290e+04,
7.63490e+04, 7.57250e+04, 7.38750e+04, 7.55470e+04, 7.64080e+04,
7.61710e+04, 7.70320e+04, 7.77190e+04, 7.39530e+04, 7.60880e+04,
7.55370e+04, 7.34150e+04, 7.47020e+04, 7.59730e+04, 7.60260e+04,
7.33120e+04, 7.28590e+04, 7.22560e+04, 7.34550e+04, 7.39520e+04,
7.40550e+04, 7.41860e+04, 7.83300e+04, 7.46570e+04, 7.55530e+04,
7.34940e+04, 7.30950e+04, 7.17090e+04, 7.24820e+04, 7.15900e+04,
6.99570e+04, 7.02670e+04, 6.88440e+04, 6.56150e+04, 6.44840e+04,
6.61080e+04, 6.89690e+04, 6.72170e+04, 6.49950e+04, 6.60210e+04,
6.53930e+04, 6.57540e+04, 6.71460e+04, 6.77860e+04, 6.64230e+04,
6.59670e+04, 6.37520e+04, 6.30930e+04, 5.99060e+04, 5.80980e+04,
5.93040e+04, 5.95250e+04, 5.80910e+04, 5.48600e+04, 5.14630e+04,
5.19830e+04, 5.11790e+04, 5.30130e+04, 5.33890e+04, 5.21250e+04,
4.98880e+04, 4.80260e+04, 4.64420e+04, 4.70720e+04, 4.79370e+04,
4.59830e+04, 4.82050e+04, 4.83380e+04, 4.52640e+04, 4.74140e+04,
4.70320e+04, 4.56090e+04, 4.42480e+04, 4.32620e+04, 4.05050e+04,
4.08700e+04, 3.98460e+04, 3.91950e+04, 4.06740e+04, 3.91660e+04,
3.67070e+04, 3.72370e+04, 3.71100e+04, 3.48810e+04, 3.55720e+04,
3.62570e+04, 3.49690e+04, 3.79110e+04, 3.38380e+04, 3.02370e+04,
3.16420e+04, 2.86710e+04, 2.41100e+04, 2.48300e+04, 2.43250e+04,
2.16140e+04, 2.33830e+04, 2.22330e+04, 1.69920e+04, 1.77220e+04,
1.72650e+04, 1.51530e+04, 1.35130e+04, 1.27670e+04, 1.07800e+04,
1.02110e+04, 8.70100e+03, 7.99800e+03, 6.69400e+03, 6.69100e+03,
4.98700e+03, 4.41000e+03, 3.72200e+03, 2.05300e+03, 2.20700e+03,
1.50200e+03, 1.46900e+03, 7.82000e+02, 3.38000e+02, 1.25000e+02]),
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., 48., 49., 50., 51., 52., 53., 54.,
55., 56., 57., 58., 59., 60., 61., 62., 63., 64., 65.,
66., 67., 68., 69., 70., 71., 72., 73., 74., 75., 76.,
77., 78., 79., 80., 81., 82., 83., 84., 85., 86., 87.,
88., 89., 90., 91., 92., 93., 94., 95., 96., 97., 98.,

file:///C:/Users/goura/Downloads/12-Numpy.html 66/73
2/1/25, 3:40 PM 12-Numpy

99., 100., 101., 102., 103., 104., 105., 106., 107., 108., 109.,
110., 111., 112., 113., 114., 115., 116., 117., 118., 119., 120.,
121., 122., 123., 124., 125., 126., 127., 128., 129., 130., 131.,
132., 133., 134., 135., 136., 137., 138., 139., 140., 141., 142.,
143., 144., 145., 146., 147., 148., 149., 150., 151., 152., 153.,
154., 155., 156., 157., 158., 159., 160., 161., 162., 163., 164.,
165., 166., 167., 168., 169., 170., 171., 172., 173., 174., 175.,
176., 177., 178., 179., 180., 181., 182., 183., 184., 185., 186.,
187., 188., 189., 190., 191., 192., 193., 194., 195., 196., 197.,
198., 199., 200., 201., 202., 203., 204., 205., 206., 207., 208.,
209., 210., 211., 212., 213., 214., 215., 216., 217., 218., 219.,
220., 221., 222., 223., 224., 225., 226., 227., 228., 229., 230.,
231., 232., 233., 234., 235., 236., 237., 238., 239., 240., 241.,
242., 243., 244., 245., 246., 247., 248., 249., 250., 251., 252.,
253., 254., 255.]),
<BarContainer object of 255 artists>)

In [76]: # structured arrays


a = np.array([1,'hello',True,1.5])
a

Out[76]: array(['1', 'hello', 'True', '1.5'], dtype='<U32')

In [77]: # name,iq,cgpa,placed

dt = np.dtype(
[
('name','U20'),
('iq',np.int32),
('cgpa',np.float64),
('placed','U20')
]
)

In [78]: dt

file:///C:/Users/goura/Downloads/12-Numpy.html 67/73
2/1/25, 3:40 PM 12-Numpy

Out[78]: dtype([('name', '<U20'), ('iq', '<i4'), ('cgpa', '<f8'), ('placed', '<U20')])

In [79]: stu = np.array(


[
('gourab',100,6.66,'Yes'),
('saurabh',120,8.9,'Yes'),
('akriti',80,7.3,'No')
],dtype=dt
)

stu

Out[79]: array([('gourab', 100, 6.66, 'Yes'), ('saurabh', 120, 8.9 , 'Yes'),


('akriti', 80, 7.3 , 'No')],
dtype=[('name', '<U20'), ('iq', '<i4'), ('cgpa', '<f8'), ('placed', '<U2
0')])

In [80]: stu['placed']

Out[80]: array(['Yes', 'Yes', 'No'], dtype='<U20')

In [81]: # save and load numpy objects


np.save('student.npy',stu)

np.swapaxes(arr, axis1, axis2)


Interchange two axes of an array.

Syntax : numpy.swapaxes(arr, axis1, axis2)


Parameters :
arr : [array_like] input array.
axis1 : [int] First axis.
axis2 : [int] Second axis.
Return : [ndarray]

In [82]: #Example
x = np.array([[1,2,3],[4,5,6]])
print(x)
print(x.shape)
print("Swapped")
x_swapped = np.swapaxes(x,0,1)
print(x_swapped)
print(x_swapped.shape)

[[1 2 3]
[4 5 6]]
(2, 3)
Swapped
[[1 4]
[2 5]
[3 6]]
(3, 2)

Note: It is not same as reshaping.

In [83]: x_reshaped = x.reshape(3,2)

file:///C:/Users/goura/Downloads/12-Numpy.html 68/73
2/1/25, 3:40 PM 12-Numpy

print(x_reshaped)

[[1 2]
[3 4]
[5 6]]

numpy.random.uniform(low=0.0, high=1.0,
size=None)
Draw samples from a uniform distribution in rangge [low - high); high not included.
https://numpy.org/doc/stable/reference/random/generated/numpy.random.uniform.html

Syntax : numpy.random.uniform(low, high, size=None)


low -> lower bound of sample; default value is 0
high -> uper bound of sample; defalut value is 1.0
size -> shape of the desired sample. If the given
shape is, e.g., (m, n, k), then m * n * k samples are drawn.

Return : Return the random samples as numpy array.

When ever we need to test our model on uniform data and we might not get truly
uniform data in real scenario, we can use this function to randomly generate data for us.

In [84]: #Example:
uniform = np.random.uniform(0, 11, 10)
print(uniform)

[ 3.71135776 7.12989059 4.05065694 10.52870675 1.54385858 9.57095984


5.2096885 8.81001827 5.72525228 7.46767483]

In [85]: #Example:
import matplotlib.pyplot as plt

# Using uniform() method


uniform = np.random.uniform(-5, 10, 1000)

plt.hist(uniform, bins = 30, density = True)


plt.show()

file:///C:/Users/goura/Downloads/12-Numpy.html 69/73
2/1/25, 3:40 PM 12-Numpy

np.count_nonzero(arr, axis=None)
This function counts the number of non-zero values in the array
https://numpy.org/doc/stable/reference/generated/numpy.count_nonzero.html

Syntax : numpy.count_nonzero(arr, axis=None)

Parameters :
arr : [array_like] The array for which to count non-zeros.

axis : [int or tuple, optional] Axis or tuple of axes along


which to count non-zeros. Default is None, meaning that non-
zeros will be counted along a flattened version of arr.

keepdims : [bool, optional] If this is set to True, the axes


that are counted are left in the result as dimensions with size
one.

Return : [int or array of int] Number of non-zero values in the


array along a given axis. Otherwise, the total number of non-
zero values in the array is returned.

In [86]: #Example

a = np.array([[0, 1, 7, 0],
[3, 0, 2, 19]])

print(np.count_nonzero(a))

print(np.count_nonzero(a, axis=0))

file:///C:/Users/goura/Downloads/12-Numpy.html 70/73
2/1/25, 3:40 PM 12-Numpy

print(np.count_nonzero(a, axis=1))

5
[1 1 2 1]
[2 3]

np.tile(A, reps)
Construct an array by repeating A the number of times given by reps . If reps has
length d , the result will have dimension of max(d, A.ndim) .

Parameters:

A: array_like
The input array.

reps: array_like
The number of repetitions of A along each axis.

Returns
c: ndarray
The tiled output array.

https://numpy.org/doc/stable/reference/generated/numpy.tile.html

In [88]: # np.tile - Example


a = np.array([0, 1, 2])
print(a)
print("Tiled")
print(np.tile(a, 2))
# Reps is given as 2 so whole array will get repeted 2 times

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

In [89]: np.tile(a, (2, 2))


# Reps is given as (2, 2)
# means along axis-0, 2 time repetition and
# along axis-1, 2 times repetition
# Axis-0 downward along the rows
# Axis -1 rightward along columns -> or inside each rows.

Out[89]: array([[0, 1, 2, 0, 1, 2],


[0, 1, 2, 0, 1, 2]])

In [90]: np.tile(a, (2, 3)) # Along axis-1 3 times repetition

Out[90]: array([[0, 1, 2, 0, 1, 2, 0, 1, 2],


[0, 1, 2, 0, 1, 2, 0, 1, 2]])

np.repeat(a, repeats, axis=None)


Repeat elements of an array. repeats parameter says no of time to repeat

file:///C:/Users/goura/Downloads/12-Numpy.html 71/73
2/1/25, 3:40 PM 12-Numpy

Parameters:
a: array_like
Input array.

repeats: int or array of ints


The number of repetitions for each element.
repeats is broadcasted to fit the shape of the given axis.

axis: int, optional


The axis along which to repeat values. By
default, use the flattened input array, and return a flat output
array.

Returns:
repeated_array: ndarray
Output array which has the same shape as a,
except along the given axis.

https://numpy.org/doc/stable/reference/generated/numpy.repeat.html

In [91]: x = np.array([[1,2],[3,4]])
print(x)
print(np.repeat(x, 2)) # Every element is getting repeted 2 times.

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

In [92]: print(x)
print(np.repeat(x, 3, axis=1)) # Alog axis-1 means rightward inside rows/ along
# Along axis-1 columns will increase

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

In [93]: print(np.repeat(x, 3, axis=0))


# Alog axis-0 means downward to rows/ along inside a column
# Along axis-0 rows will increase

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

np.allclose
Returns True if two arrays are element-wise equal within a tolerance.

The tolerance values are positive, typically very small numbers. The relative difference
(rtol * abs(b)) and the absolute difference atol are added together to compare
against the absolute difference between a and b .

If the following equation is element-wise True, then allclose returns True .

file:///C:/Users/goura/Downloads/12-Numpy.html 72/73
2/1/25, 3:40 PM 12-Numpy

absolute(a - b) <= (atol + rtol * absolute(b))

Syntax : numpy.allclose(arr1, arr2, rtol, atol, equal_nan=False)

Parameters :
arr1 : [array_like] Input 1st array.
arr2 : [array_like] Input 2nd array.
rtol : [float] The relative tolerance parameter.
atol : [float] The absolute tolerance parameter.
equal_nan : [bool] Whether to compare NaN’s as equal.
If True, NaN’s in arr1 will be considered equal to
NaN’s in arr2 in the output array.

Return : [ bool] Returns True if the two arrays are equal within
the given tolerance, otherwise it returns False.

https://numpy.org/doc/stable/reference/generated/numpy.allclose.html
https://www.geeksforgeeks.org/numpy-allclose-in-python/

In [94]: #np.allclose example


#Comparing -
a = np.array([1.1, 1.2, 1.0001])
b = np.array([1., 1.02, 1.001])
print(a)
print(b)
print(np.abs(a-b))

# will return false


print(np.allclose(a,b))
# will return true, as i incearse the absolute tolerance value
print(np.allclose(a,b, atol=0.2))

[1.1 1.2 1.0001]


[1. 1.02 1.001]
[0.1 0.18 0.0009]
False
True

In [95]: # Nan will be taken as different


print(np.allclose([1.0, np.nan], [1.0, np.nan]))

# Nan will be treated as same


print(np.allclose([1.0, np.nan], [1.0, np.nan], equal_nan=True))

False
True

In [ ]:

file:///C:/Users/goura/Downloads/12-Numpy.html 73/73

You might also like