Efficient Computing with NumPy
Efficient Computing with 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.
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.
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.
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.
a = np.array([1,2,3,4,5])
print(type(a))
a
<class 'numpy.ndarray'>
Out[1]: array([1, 2, 3, 4, 5])
print(b)
[[1 2 3]
[4 5 6]]
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 [6]: # Creating a NumPy array with values from 1 to 10, with a step of 2
np.arange(1, 11, 2)
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)
In [10]: # Creating a 3x4 NumPy array with random values between 0 and 1
np.random.random((3, 4))
In [11]: # Creating a NumPy array of 10 evenly spaced values between -10 and 10
np.linspace(-10, 10, 10)
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
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]]]
Out[16]: 3
Out[17]: (10,)
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)
Array Operations
file:///C:/Users/goura/Downloads/12-Numpy.html 4/73
2/1/25, 3:40 PM 12-Numpy
a2
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
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.]
38.666666666666664
35.0
24.289915602982237
590.0
np.sin(a1)
np.dot(a2, a3)
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)
In [37]: a1
In [38]: a2
In [39]: a3
[[4, 5],
[6, 7]]])
Out[43]: 4
Out[44]: 6
a2[2,3]
Out[45]: 11
Out[46]: 5
file:///C:/Users/goura/Downloads/12-Numpy.html 7/73
2/1/25, 3:40 PM 12-Numpy
In [49]: # Slicing the 2D array a2 to select rows from index 1 onwards and columns from i
a2[1:, 1:3]
In [50]: # Slicing the 2D array a2 to select every second row (::2) and every third colum
a2[::2, ::3]
In [51]: # Slicing the 2D array a2 to select every second row (::2) and every second colu
a2[::2, 1::2]
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
[[ 9, 10, 11],
[12, 13, 14],
[15, 16, 17]],
In [53]: a3[1]
In [54]: a3[::2]
In [55]: a3[0,1]
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]
In [57]: a3[2,1:,1:]
In [58]: a3[::2,0,::2]
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
[0 1 2 3]
[4 5 6 7]
[ 8 9 10 11]
[[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
In [65]: a3
[[ 9, 10, 11],
[12, 13, 14],
[15, 16, 17]],
file:///C:/Users/goura/Downloads/12-Numpy.html 10/73
2/1/25, 3:40 PM 12-Numpy
Stacking
In [67]: # Horizontal Stacking
a4 = np.arange(12).reshape(3,4)
a5 = np.arange(12,24).reshape(3,4)
In [68]: a4
In [69]: a5
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]])
Splitting
In [73]: a4
file:///C:/Users/goura/Downloads/12-Numpy.html 11/73
2/1/25, 3:40 PM 12-Numpy
---------------------------------------------------------------------------
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)
a5
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)
Advanced Numpy
Numpy array vs Python List
import time
# Start time
start = time.time()
3.600071907043457
In [10]: # Measuring execution time for summing two NumPy arrays element-wise
import numpy as np
import time
# Start time
file:///C:/Users/goura/Downloads/12-Numpy.html 13/73
2/1/25, 3:40 PM 12-Numpy
start = time.time()
0.19878029823303223
In [11]: 3.60/0.19
Out[11]: 18.94736842105263
import sys
89095160
In [5]: a = np.arange(10000000)
sys.getsizeof(a)
Out[5]: 40000112
Out[6]: 20000112
Advance Indexing
In [14]: # Advance indexing and slicing
a = np.arange(12).reshape(4,3)
a
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
In [19]: # Accessing elements at indices 0, 2, 3, and 5 from the NumPy array `b`
b[[0, 2, 3, 5]]
In [20]: # Attempting to access specific columns (0, 2, 3) from all rows of a 2D NumPy ar
b[:, [0, 2, 3]]
a = np.random.randint(1,100,24).reshape(6,4)
a
a>50
In [23]: # filter
a[a>50]
Out[23]: array([86, 78, 91, 77, 74, 91, 94, 63, 73, 85, 86, 52])
a%2 == 0
file:///C:/Users/goura/Downloads/12-Numpy.html 15/73
2/1/25, 3:40 PM 12-Numpy
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[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.
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
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.
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
[[ 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]]
a = np.arange(12).reshape(3, 4)
b = np.arange(3)
print(a)
print(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,)
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)
[[0 1 2]]
[[0]
[1]
[2]]
[[0 1 2]
[1 2 3]
[2 3 4]]
a = np.arange(3).reshape(1, 3)
b = np.arange(4).reshape(4, 1)
print(a)
print(b)
[[0 1 2]]
[[0]
[1]
[2]
[3]]
[[0 1 2]
[1 2 3]
[2 3 4]
[3 4 5]]
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)
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)
Out[41]: 45
In [42]: # Trigonometric
np.sin(a)
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)
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])
mse(actual,predicted)
Out[47]: 476.56
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
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
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)
In [53]: # y = x^2
x = np.linspace(-10,10,100)
y = x**2
plt.plot(x,y)
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)
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)
In [56]: # sigmoid
x = np.linspace(-10,10,100)
y = 1/(1+np.exp(-x))
plt.plot(x,y)
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
In [59]: np.sort(a)
Out[59]: array([ 5, 10, 28, 40, 40, 44, 53, 53, 58, 58, 78, 79, 89, 91, 96])
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
np.sort(b,axis = 0)
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
In [66]: np.append(b,np.ones((b.shape[0],1)),axis = 1)
In [67]: np.append(b,np.random.random((b.shape[0],1)),axis = 1)
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)
In [70]: np.concatenate((c,d),axis = 1)
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)
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
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)
np.where(a>50,0,a)
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
In [85]: np.argmax(b,axis = 0)
In [86]: np.argmax(b,axis = 1)
In [87]: # np.argmin
np.argmin(a)
Out[87]: 1
In [88]: np.argmin(b,axis = 0)
In [89]: np.argmin(b,axis = 1)
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
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 [95]: np.cumsum(b,axis = 1)
In [96]: # np.cumprod
np.cumprod(a)
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])
np.corrcoef
Return Pearson product-moment correlation coefficients.
np.corrcoef(salary,experience)
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])
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
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)
In [111… np.flip(b,axis = 0)
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)
In [119… np.intersect1d(g,k)
In [120… np.setdiff1d(g,k)
In [121… np.setdiff1d(k,g)
In [122… np.setxor1d(g,k)
In [123… np.in1d(g,1)
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])
Out[125… array([75, 75, 25, 40, 53, 75, 75, 53, 75, 58, 44, 58, 40, 75, 28])
[[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
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
[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]
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).
file:///C:/Users/goura/Downloads/12-Numpy.html 35/73
2/1/25, 3:40 PM 12-Numpy
Description:
[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
[[1,1,1,1],
[1,0,0,1],
[1,0,0,1],
[1,1,1,1]]
file:///C:/Users/goura/Downloads/12-Numpy.html 37/73
2/1/25, 3:40 PM 12-Numpy
Out[8]: array([ 71, 123, 104, 60, 77, 112, 72, 24, 57, 50])
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:
Output Format:
Example 1:
Input:
1 2 3 4 -8 -10
Output:
Example 1:
Input:
np.array([])
Output:
elements_count : 0
Example 2:
Input:
np.array([1, 2])
Output:
elements_count : 2
Out[14]: 6
file:///C:/Users/goura/Downloads/12-Numpy.html 39/73
2/1/25, 3:40 PM 12-Numpy
zi
e
→
σ(z )i =
K zj
∑ e
j=i
Example 1:
Input:
Input:
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]]
[[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]]
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:
Input:
Input:
file:///C:/Users/goura/Downloads/12-Numpy.html 42/73
2/1/25, 3:40 PM 12-Numpy
Output:
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')
file:///C:/Users/goura/Downloads/12-Numpy.html 43/73
2/1/25, 3:40 PM 12-Numpy
Result-> [6 3 1 7 8]
a[b>a] = b[a<b]
a
https://en.wikipedia.org/wiki/Normalization_(statistics)
There are different form of normalisation for this question use below formula.
X − Xmin
Xnormalized =
Xmax − Xmin
In [22]: # Given
arr1=np.random.randint(low=1, high=10000, size=40).reshape(8,5)
arr1
file:///C:/Users/goura/Downloads/12-Numpy.html 44/73
2/1/25, 3:40 PM 12-Numpy
Output: The output should be the nth largest item out of the array
Out[25]: 34
file:///C:/Users/goura/Downloads/12-Numpy.html 45/73
2/1/25, 3:40 PM 12-Numpy
Out[28]: 38
result-> [1 2 0 4 0 0 7 0]
arr = np.arrange(10)
indexes = [0,3,4,9]
array = [1,2,3]
result array -> [1 1 1 2 2 2 3 3 3]
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
import numpy as np
file:///C:/Users/goura/Downloads/12-Numpy.html 47/73
2/1/25, 3:40 PM 12-Numpy
In [34]: #2
np.nan_to_num(arr)
http://en.wikipedia.org/wiki/Cauchy_matrix
x = numpy.array([1,2,3,4]).reshape((-1, 1)
y = numpy.array([5,6,7])
1/(x-y)
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.
file:///C:/Users/goura/Downloads/12-Numpy.html 48/73
2/1/25, 3:40 PM 12-Numpy
plt.plot(x,y)
plt.plot(x,y)
file:///C:/Users/goura/Downloads/12-Numpy.html 49/73
2/1/25, 3:40 PM 12-Numpy
shape of a- (3,2,2)
shape of b- (2,2)
# 4 3 3 5
# 2 5
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
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]]
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]]
Given Array-
file:///C:/Users/goura/Downloads/12-Numpy.html 52/73
2/1/25, 3:40 PM 12-Numpy
[[ 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]]
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]]
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])
X = 6
file:///C:/Users/goura/Downloads/12-Numpy.html 54/73
2/1/25, 3:40 PM 12-Numpy
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))
[[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
Interview Questions
In [52]: import numpy as np
import warnings
warnings.filterwarnings('ignore')
Out[53]: array([-10., -9., -8., -7., -6., -5., -4., -3., -2., -1., 0.,
1., 2., 3., 4., 5., 6., 7., 8., 9.])
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.]])
file:///C:/Users/goura/Downloads/12-Numpy.html 58/73
2/1/25, 3:40 PM 12-Numpy
zz = func(xx,yy)
zz
file:///C:/Users/goura/Downloads/12-Numpy.html 59/73
2/1/25, 3:40 PM 12-Numpy
file:///C:/Users/goura/Downloads/12-Numpy.html 60/73
2/1/25, 3:40 PM 12-Numpy
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))
[[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)
In [60]: np.random.seed(0)
np.random.randint(1,100,12).reshape(3,4)
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
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
In [65]: np.random.choice(a,3,replace=False)
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
In [71]: np.flip(a)
In [73]: # negative
plt.imshow(255 - img)
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,:])
file:///C:/Users/goura/Downloads/12-Numpy.html 65/73
2/1/25, 3:40 PM 12-Numpy
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 [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
stu
In [80]: stu['placed']
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)
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
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)
In [85]: #Example:
import matplotlib.pyplot as plt
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
Parameters :
arr : [array_like] The array for which to count non-zeros.
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
[0 1 2]
Tiled
[0 1 2 0 1 2]
file:///C:/Users/goura/Downloads/12-Numpy.html 71/73
2/1/25, 3:40 PM 12-Numpy
Parameters:
a: array_like
Input 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]]
[[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 .
file:///C:/Users/goura/Downloads/12-Numpy.html 72/73
2/1/25, 3:40 PM 12-Numpy
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/
False
True
In [ ]:
file:///C:/Users/goura/Downloads/12-Numpy.html 73/73