1. Module: M2-R5: Web Designing & Publishing
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
home-2741413_960_720.png
Index
❑ NumPy Introduction
❑ The need of NumPy
❑ Importance and features of NumPy
❑ Advantages of NumPy
❑ NumPy Environment Setup
❑ Using Numpy
❑ Ndarray in NumPy
❑ Creating a ndarray
❑ Accessing Elements (Indexing and
Slicing)
1
❑ Basic Array Operation
❑ NumPy Array Axis
❑ Understanding Array Dimensions
❑ Higher-Dimensional Arrays
❑ Important Attributes of an ndarray
Objects
❑ Reshaping the array objects
❑ Array Concatenation and Stacking
❑ Splitting Arrays
❑ Flattening Arrays with flatten()
❑ NumPy Datatypes
2. Module: M2-R5: Web Designing & Publishing
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
home-2741413_960_720.png
Index
2
❑ Trigonometric and Statistical Functions
❑ Introduction to Broadcasting
❑ NumPy Array Iteration
❑ NumPy Bitwise Operators
❑ NumPy Sorting and Searching
❑ Assignment
❑ Numpy Array from Existing Data
❑ Array Creation using numpy.arange()
❑ Array Creation using numpy.linspace()
❑ Creating Identity and Diagonal Matrices
❑ Finding square root and standard
deviation
❑ Linear Algebra Operations(dot products,
matrix multiplication)
3. Module: M2-R5: Web Designing & Publishing
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
home-2741413_960_720.png
NumPy Introduction
3
❑ NumPy stands for numeric python which is a python package for the computation and
processing of the multidimensional and single dimensional array elements.
❑ Travis Oliphant created NumPy package in 2005 by injecting the features of the
ancestor module Numeric into another module Numarray.
❑ It is an extension module of Python which is mostly written in C. It provides various
functions which are capable of performing the numeric computations with a high speed.
4. Module: M2-R5: Web Designing & Publishing
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
home-2741413_960_720.png
The need of NumPy
❑ With the revolution of data science, data analysis libraries like NumPy, SciPy, Pandas,
etc. have seen a lot of growth. With a much easier syntax than other programming
languages, python is the first choice language for the data scientist.
❑ NumPy provides a convenient and efficient way to handle the vast amount of data.
NumPy is also very convenient with Matrix multiplication and data reshaping. NumPy
is fast which makes it reasonable to work with a large set of data.
❑ NumPy provides a convenient and efficient way to handle the vast amount of data.
NumPy is also very convenient with Matrix multiplication and data reshaping. NumPy
is fast which makes it reasonable to work with a large set of data.
4
5. Module: M2-R5: Web Designing & Publishing
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
home-2741413_960_720.png
Importance and features of NumPy
5
❑ Efficient Data Handling:
- Fast and efficient processing of large datasets.
- Provides support for array-oriented computing.
❑ Matrix Operations:
- Built-in functions for matrix multiplication, linear algebra, and data reshaping.
- Supports Fourier Transform and other scientific computations.
❑ Multidimensional Arrays:
- Efficient implementation and manipulation of multidimensional arrays.
- Convenient tools for data reshaping and processing.
❑ Integration with Other Libraries:
- Works seamlessly with SciPy and Matplotlib.
- Widely used as a replacement for MATLAB due to Python’s simplicity and versatility.
6. Module: M2-R5: Web Designing & Publishing
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
home-2741413_960_720.png
Advantages of NumPy
❑ NumPy performs array-oriented computing.
❑ It efficiently implements the multidimensional arrays.
❑ It performs scientific computations.
❑ It is capable of performing Fourier Transform and reshaping the data stored in
multidimensional arrays.
❑ NumPy provides the in-built functions for linear algebra and random number
generation.
6
7. Module: M2-R5: Web Designing & Publishing
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
home-2741413_960_720.png
NumPy Environment Setup
7
NumPy doesn't come bundled with Python. We have to install it using the python pip
installer. Execute the following command.
❑ Open Command Prompt or Terminal:
To install NumPy, you need to use the command line.
open the Command Prompt by typing `cmd` in the search bar.
❑ Install NumPy Using pip:
Type the following command and press Enter:
pip install numpy
This command will download and install the latest version of NumPy.
8. Module: M2-R5: Web Designing & Publishing
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
home-2741413_960_720.png
❑ Import the numpy package in a python program as:
import numpy
or
import numpy as np
9
9. Module: M2-R5: Web Designing & Publishing
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
home-2741413_960_720.png
❑ Ndarray is the n-dimensional array object defined in the numpy which stores the collection of the
similar type of elements. In other words, we can define a ndarray as the collection of the data type
(dtype) objects.
❑ The ndarray object can be accessed by using the 0 based indexing. Each element of the Array object
contains the same size in the memory.
Key Features:
❑ 0-Based Indexing: Access elements using indices starting from 0.
❑ Memory Efficiency: Each element occupies the same amount of memory space.
Why Use `ndarray`?
❑ Supports efficient computation with large datasets.
❑ Enables fast operations on arrays like slicing, reshaping, and broadcasting.
10
10. Module: M2-R5: Web Designing & Publishing
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
home-2741413_960_720.png
Creating a ndarray
10
❑ The ndarray object can be created by using the array array() function of the numpy module.
❑ Step 1: Import NumPy Module
import numpy
❑ Step 2: Use the `array` Routine
Create an `ndarray` using `numpy.array()`.
Example:
#Create a Simple Array:
import numpy
a = numpy.array([1, 2, 3])
print(a)
Output:
[1 2 3]
11. Module: M2-R5: Web Designing & Publishing
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
home-2741413_960_720.png
Continue…
11
❑ To create a two-dimensional array object, use the following syntax.
# ndarray of two dimensions
import numpy as np
a = np.array([[1,2,3], [4,5,6], [7,8,9]])
❑ To create a multi-dimensional array object, use the following syntax.
# ndarray of more than one dimensions
import numpy as np
a = np.array([[values…..], [values…..]])
12. Module: M2-R5: Web Designing & Publishing
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
home-2741413_960_720.png
Accessing Elements (Indexing and Slicing)
12
❑ Indexing allows access to specific elements in an array, while slicing provides a way to extract
subsets of the array. NumPy supports both simple and advanced indexing techniques.
❑ Understanding how to access and manipulate elements in arrays is fundamental for data analysis
and manipulation.
Examples:
Indexing:
import numpy as np
a = np.array([1, 2, 3, 4])
print(a[0])
Output: 1
b = np.array([[1, 2, 3], [4, 5, 6]])
print(b[1, 2])
Output: 6
13. Module: M2-R5: Web Designing & Publishing
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
home-2741413_960_720.png
Continue…
13
❑ Slicing in the NumPy array is the way to extract a range of elements from an array. Slicing in the array
is performed in the same way as it is performed in the python list.
❑ Slicing extracts a subset of an array using a range of indices. It returns a new array containing elements
from the specified start index up to, but not including, the stop index.
Example 1:
import numpy as np
a = np.array([[1,2],[3,4],[5,6]])
print(a[0,1])
print(a[2,0])
Output:
2 5
The above program prints the 2nd element from the 0th index and 0th element from the 2nd index of the
array.
14. Module: M2-R5: Web Designing & Publishing
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
home-2741413_960_720.png
Basic Array Operation
14
❑ Arithmetic Operations: Element-wise addition, subtraction, multiplication, and division:
import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
print(a + b)
Output: [5 7 9]
print(a * b)
Output: [ 4 10 18]
❑ Array Methods: `sum()`, `mean()`, `max()`, `min()`:
import numpy as np
a = np.array([1, 2, 3])
print(a.sum()) # Output: 6
print(a.mean()) # Output: 2.0
15. Module: M2-R5: Web Designing & Publishing
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
home-2741413_960_720.png
Continue….
15
❑ The NumPy provides the max(), min(), and sum() functions which are used to find
the maximum, minimum, and sum of the array elements respectively.
❑ max(): max() function is used to display largest value from a given array list.
Example 1:
import numpy as np
x = np.array([1,2,3,10,15,4])
print("The maximum element:", x.max())
Output:
The maximum element: 15
16. Module: M2-R5: Web Designing & Publishing
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
home-2741413_960_720.png
Continue….
16
❑ min(): The min() function is used to display smallest value from a given array list.
Example 1:
import numpy as np
x = np.array([1,2,3,10,15,4])
print("The minimum element:", x.min())
Output:
The minimum element: 1
17. Module: M2-R5: Web Designing & Publishing
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
home-2741413_960_720.png
Continue….
17
❑ sum(): The sum() function is used to display total of the values.
Example 1:
import numpy as np
a = np.array([1,2,3,10,15,4])
print("The some of elements:",a.sum())
Output:
The some of elements: 35
18. Module: M2-R5: Web Designing & Publishing
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
home-2741413_960_720.png
NumPy Array Axis
18
A NumPy multi-dimensional array is represented by the axis.
❑ axis=0 represents the columns
❑ axis =1 represents the rows.
19. Module: M2-R5: Web Designing & Publishing
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
home-2741413_960_720.png
Example
19
import numpy as np
a = np.array([[1,2,30],[10,15,4]])
print("The array:",a)
print("The maximum elements of columns:",a.max(axis = 0))
print("The minimum element of rows",a.min(axis = 1))
print("The sum of all rows",a.sum(axis = 1))
Output:
The array: [[1 2 30]
[10 15 4]]
The maximum elements of columns: [10 15 30]
The minimum element of rows [1 4] The sum of all rows [33 29]
20. Module: M2-R5: Web Designing & Publishing
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
home-2741413_960_720.png
Understanding Array Dimensions
20
❑ Array Dimensions: Refers to the number of axes or coordinates needed to index an
array.
❑ 1-D Array: A simple list of elements.
❑ 2-D Array: A matrix with rows and columns.
❑ Higher Dimensions: Arrays with more than two axes, useful for more complex data
structures.
Example for 1-D Array:
import numpy as np
a = np.array([1, 2, 3])
print(a.ndim) # Output: 1
print(a.shape) # Output: (3,)
21. Module: M2-R5: Web Designing & Publishing
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
home-2741413_960_720.png
Example
21
Example for 2-D Array:
import numpy as np
b = np.array([[1, 2], [3, 4]])
print(b.ndim)
print(b.shape)
Output:
2
(2, 2)
22. Module: M2-R5: Web Designing & Publishing
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
home-2741413_960_720.png
Higher-Dimensional Arrays
22
- 3-D Array: Contains multiple 2-D arrays (e.g., a stack of matrices).
- N-D Arrays: Can have more than three dimensions, used for complex data like multi-
dimensional data grids.
Code Example for 3-D Array:
import numpy as np
c = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
print(c.ndim)
Output: 3
print(c.shape)
Output: (2, 2, 2)
23. Module: M2-R5: Web Designing & Publishing
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
home-2741413_960_720.png
Important Attributes of an ndarray Objects
23
❑ ndarray.ndim
Returns the number of dimensions (axes) of the array.
Example:
a = numpy.array([[1, 2, 3], [4, 5, 6]])
print(a.ndim)
Output: 2
❑ ndarray.shape
Returns a tuple representing the size of the array in each dimension. For a matrix with n
rows and m columns, shape will be (n,m). The length of the shape tuple is therefore the
number of axes, ndim.
24. Module: M2-R5: Web Designing & Publishing
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
home-2741413_960_720.png
Continue…
24
Example:
import numpy as np
a = numpy.array([[1, 2, 3], [4, 5, 6]])
print(a.shape)
Output:
(2, 3)
25. Module: M2-R5: Web Designing & Publishing
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
home-2741413_960_720.png
25
❑ ndarray.size
Returns the total number of elements in the array.
Example:
a = numpy.array([[1, 2, 3], [4, 5, 6]])
print(a.size)
Output: 6
❑ ndarray.dtype
Returns the data type of the elements in the array.
Example:
a = numpy.array([1, 2, 3])
print(a.dtype)
Output: int64 (or int32, depending on the system)
Continue…
26. Module: M2-R5: Web Designing & Publishing
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
home-2741413_960_720.png
26
❑ ndarray.itemsize
Returns the **size (in bytes) of each element in the array.
Example:
a = numpy.array([1, 2, 3])
print(a.itemsize)
Output: 8 (if dtype is int64)
❑ ndarray.nbytes
Returns the **total number of bytes** consumed by the elements of the array.
Example:
a = numpy.array([1, 2, 3])
print(a.nbytes)
Output: 24 (3 elements * 8 bytes each)
Continue…
27. Module: M2-R5: Web Designing & Publishing
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
home-2741413_960_720.png
26
❑ ndarray.T
Returns the transpose of the array.
Example:
a = numpy.array([[1, 2, 3], [4, 5, 6]])
print(a.T)
Output: [[1, 4], [2, 5], [3, 6]]
❑ ndarray.flat
Returns a 1-D iterator over the array, allowing iteration over all elements in a
flattened format.
Example:
a = np.array([[1, 2], [3, 4]])
print(list(a.flat))
Output: [1, 2, 3, 4]
Continue…
28. Module: M2-R5: Web Designing & Publishing
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
home-2741413_960_720.png
27
❑ reshape() is used to reshape array objects. By the shape of the array, we mean the
number of rows and columns of a multi-dimensional array. However, the numpy
module provides us the way to reshape the array by changing the number of rows and
columns of the multi-dimensional array.
Example:
import numpy as np
a = np.array([[1,2],[3,4],[5,6]])
print("printing the original array..")
print(a)
a=a.reshape(2,3)
print("printing the reshaped array..")
print(a)
Reshaping the array objects
29. Module: M2-R5: Web Designing & Publishing
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
home-2741413_960_720.png
27
Output:
printing the original array..
[[1 2]
[3 4]
[5 6]]
printing the reshaped array..
[[1 2 3]
[4 5 6]]
Continue….
30. Module: M2-R5: Web Designing & Publishing
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
home-2741413_960_720.png
Array Concatenation and Stacking
30
❑ Concatenation : The concatenate() function allows you to join arrays along an
existing axis. For example, you can join two 1D arrays or two 2D arrays along
rows or columns.
❑ Stacking : vstack() and hstack() are used for vertical and horizontal stacking of
arrays, respectively. vstack() stacks arrays vertically (row-wise), while hstack()
stacks them horizontally (column-wise).
Example:
arr1 = np.array([1, 2])
arr2 = np.array([3, 4])
concatenated_arr = np.concatenate((arr1, arr2))
stacked_arr = np.vstack((arr1, arr2))
print(concatenated_arr)
print(stacked_arr)
Output:
[1 2 3 4]
[[1 2] [3 4]]
31. Module: M2-R5: Web Designing & Publishing
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
home-2741413_960_720.png
Splitting Arrays
31
❑ split() function
The `split()` function is used to split an array into multiple sub-arrays. You can specify
how many parts the array should be split into, and it returns a list of sub-arrays.
Example:
arr = np.array([1, 2, 3, 4, 5, 6])
split_arr = np.split(arr, 3)
print(split_arr)
Output:
[array([1, 2]), array([3, 4]), array([5, 6])]
Explanation:
Here, the array `[1, 2, 3, 4, 5, 6]` is split into 3 equal sub-arrays: `[1, 2]`, `[3, 4]`, and `[5,
6]`.
32. Module: M2-R5: Web Designing & Publishing
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
home-2741413_960_720.png
Flattening Arrays with flatten()
32
❑ Flattening Arrays with flatten() :
The `flatten()` method converts a multi-dimensional array into a 1D array. This is particularly
useful when you need to work with the array data in a linear form.
Example:
arr = np.array([[1, 2, 3], [4, 5, 6]])
flat_arr = arr.flatten()
print(flat_arr)
Output:
[1 2 3 4 5 6]
Explanation:
The 2D array `[[1, 2, 3], [4, 5, 6]]` is flattened into a 1D array `[1, 2, 3, 4, 5, 6]`.
This helps to easily manipulate or iterate over the array data.
33. Module: M2-R5: Web Designing & Publishing
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
home-2741413_960_720.png
NumPy Datatypes
33
SN Data type Description
1 bool_ It represents the boolean value indicating true or false. It is stored as a byte.
2 int_ It is the default type of integer. It is identical to long type in C that contains 64 bit or 32-bit integer.
3 intc It is similar to the C integer (c int) as it represents 32 or 64-bit int.
4 intp It represents the integers which are used for indexing.
5 int8 It is the 8-bit integer identical to a byte. The range of the value is -128 to 127.
6 int16 It is the 2-byte (16-bit) integer. The range is -32768 to 32767.
7 int32 It is the 4-byte (32-bit) integer. The range is -2147483648 to 2147483647.
8 int64 It is the 8-byte (64-bit) integer. The range is -9223372036854775808 to 9223372036854775807.
9 uint8 It is the 1-byte (8-bit) unsigned integer.
10 uint16 It is the 2-byte (16-bit) unsigned integer.
11 uint32 It is the 4-byte (32-bit) unsigned integer.
34. Module: M2-R5: Web Designing & Publishing
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
home-2741413_960_720.png
Continue….
34
SN Data type Description
12 uint64 It is the 8 bytes (64-bit) unsigned integer.
13 float_ It is identical to float64.
14 float16
It is the half-precision float. 5 bits are reserved for the exponent. 10 bits are reserved for
mantissa, and 1 bit is reserved for the sign.
15 float32
It is a single precision float. 8 bits are reserved for the exponent, 23 bits are reserved for
mantissa, and 1 bit is reserved for the sign.
16 float64
It is the double precision float. 11 bits are reserved for the exponent, 52 bits are reserved
for mantissa, 1 bit is used for the sign.
17 complex_ It is identical to complex128.
35. Module: M2-R5: Web Designing & Publishing
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
home-2741413_960_720.png
Continue….
35
SN Data type Description
12 uint64 It is the 8 bytes (64-bit) unsigned integer.
13 float_ It is identical to float64.
14 float16
It is the half-precision float. 5 bits are reserved for the exponent. 10 bits are reserved for
mantissa, and 1 bit is reserved for the sign.
15 float32
It is a single precision float. 8 bits are reserved for the exponent, 23 bits are reserved for
mantissa, and 1 bit is reserved for the sign.
16 float64
It is the double precision float. 11 bits are reserved for the exponent, 52 bits are reserved for
mantissa, 1 bit is used for the sign.
17 complex_ It is identical to complex128.
36. Module: M2-R5: Web Designing & Publishing
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
home-2741413_960_720.png
Numpy Array from Existing Data
36
❑ NumPy provides us the way to create an array by using the existing data.
❑ This routine is used to create an array by using the existing data in the form of lists,
or tuples. This routine is useful in the scenario where we need to convert a python
sequence into the numpy array object.
numpy.asarray(sequence, dtype = None, order = None)
❑ It accepts the following parameters.
sequence: It is the python sequence which is to be converted into the python array.
dtype: It is the data type of each item of the array.
order: It can be set to C or F. The default is C.
37. Module: M2-R5: Web Designing & Publishing
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
home-2741413_960_720.png
Continue…
37
❑ Creating numpy array using the list
import numpy as np
l=[1,2,3,4,5,6,7]
a = np.asarray(l)
❑ Creating a numpy array using Tuple
import numpy as np
l=(1,2,3,4,5,6,7)
a = np.asarray(l)
❑ Creating a numpy array using more than one list
import numpy as np
l=[[1,2,3,4,5,6,7],[8,9,12,13,14,15,16]]
a = np.asarray(l)
38. Module: M2-R5: Web Designing & Publishing
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
home-2741413_960_720.png
Array Creation using numpy.arange()
38
❑ Using numpy.arange()
numpy.arange() creates arrays with evenly spaced values within a specified range. It is similar
to Python's range() but returns an array instead of a list.
Example:
import numpy as np
a = np.arange(5)
b = np.arange(1, 10, 2)
print(a)
print(b)
Output:
[0 1 2 3 4]
[1 3 5 7 9]
39. Module: M2-R5: Web Designing & Publishing
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
home-2741413_960_720.png
Array Creation using numpy.linspace()
39
❑ Using numpy.linspace() :
numpy.linspace() generates arrays with a specified number of evenly spaced values between
a start and end point. This is useful for creating ranges with a specific number of elements.
Example:
import numpy as np
a = np.linspace(0, 1, 5)
b = np.linspace(1, 10, 4)
print(a)
print(b)
Output:
[0. 0.25 0.5 0.75 1. ]
[ 1. 4. 7. 10.]
40. Module: M2-R5: Web Designing & Publishing
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
home-2741413_960_720.png
Creating Identity and Diagonal Matrices
40
❑ Identity matrices have ones on the diagonal and zeros elsewhere. Diagonal matrices have
non-zero values only on the diagonal. Both are important for linear algebra operations.
Example:
import numpy as np
a = np.eye(3) # Creates a 3x3 identity matrix
b = np.diag([1, 2, 3]) # Creates a diagonal matrix with [1, 2, 3] on the diagonal
print(a)
print(b)
Output: [[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
[[1 0 0]
[0 2 0]
[0 0 3]]
41. Module: M2-R5: Web Designing & Publishing
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
home-2741413_960_720.png
Finding square root and standard deviation
41
❑ The sqrt() and std() functions associated with the numpy array are used to find the square
root and standard deviation of the array elements respectively.
❑ Standard deviation means how much each element of the array varies from the mean value of
the numpy array.
Example:
import numpy as np
a = np.array([[1,2,30],[10,15,4]])
print(“Square root: ”np.sqrt(a))
print(“Standard Deviation ”np.std(a))
Output:
Square Root: [[1. 1.41421356 5.47722558]
[3.16227766 3.87298335 2. ]]
Standard Deviation: 10.044346115546242
42. Module: M2-R5: Web Designing & Publishing
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
home-2741413_960_720.png
Linear Algebra Operations(dot products, matrix multiplication)
42
❑ NumPy provides efficient functions for linear algebra operations such as dot products, matrix
multiplication, and solving linear systems. The `dot()` function is used for matrix multiplication, while
`@` is the shorthand operator for dot products.
Example:
arr1 = np.array([[1, 2], [3, 4]])
arr2 = np.array([[5, 6], [7, 8]])
dot_product = np.dot(arr1, arr2)
matrix_mult = arr1 @ arr2 # Same as np.dot(arr1, arr2)
print(dot_product)
print(matrix_mult)
Output:
[[19 22]
[43 50]]
[[19 22]
[43 50]]
43. Module: M2-R5: Web Designing & Publishing
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
home-2741413_960_720.png
Trigonometric and Statistical Functions
43
❑ NumPy includes a wide range of trigonometric functions (such as `sin()`, `cos()`, `tan()`) and
statistical functions (such as `min()`, `max()`, `percentile()`) for handling scientific computations and
data analysis.
Example:
angles = np.array([0, np.pi / 2, np.pi])
sine_values = np.sin(angles)
max_val = np.max(angles)
print(sine_values) # Sine of the angles
print(max_val) # Maximum value in the array
Output:
[0.0000000e+00 1.0000000e+00 1.2246468e-16]
3.141592653589793
Explanation:
The `sin()` function calculates the sine of each angle in radians, and `max()` returns the maximum
value from the array of angles.
44. Module: M2-R5: Web Designing & Publishing
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
home-2741413_960_720.png
Continue…
44
Numpy statistical functions:
❑ numpy.amin() and numpy.amax() :These functions are used to find the minimum
and maximum of the array elements along the specified axis respectively.
❑ Syntax: amin(array_name, axis)
amax(array_name, axis)
❑ The axis will be
1: for row wise operation
0: for column wise operation
45. Module: M2-R5: Web Designing & Publishing
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
home-2741413_960_720.png
Example
45
import numpy as np
array = np.array([[4, 9, 2], [7, 1, 8], [6, 3, 5]])
# Finding the minimum and maximum along axis 1 (row-wise)
min_row = np.amin(array, axis=1)
max_row = np.amax(array, axis=1)
# Finding the minimum and maximum along axis 0 (column-wise)
min_col = np.amin(array, axis=0)
max_col = np.amax(array, axis=0)
print("Original Array:n", array)
print("nRow-wise minimum:", min_row)
print("Row-wise maximum:", max_row)
print("nColumn-wise minimum:", min_col)
print("Column-wise maximum:", max_col)
46. Module: M2-R5: Web Designing & Publishing
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
home-2741413_960_720.png
Output
46
Original Array:
[[4 9 2] [7 1 8] [6 3 5]]
Row-wise minimum: [2 1 3]
Row-wise maximum: [9 8 6]
Column-wise minimum: [4 1 2]
Column-wise maximum: [7 9 8]
Note: axis=1 performs the operation row-wise (across the columns for each row).
axis=0 performs the operation column-wise (across the rows for each column).
47. Module: M2-R5: Web Designing & Publishing
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
home-2741413_960_720.png
Introduction to Broadcasting
47
❑ Broadcasting is a technique in NumPy that allows you to perform operations on arrays of
different shapes as if they have the same shape. Smaller arrays are automatically
“broadcasted” to match the shape of the larger array.
Example:
If you add a scalar (like a single number) to an array, NumPy will "stretch" the scalar across
the array:
arr = np.array([1, 2, 3])
result = arr + 5 # Broadcasting the scalar 5
print(result)
Output:
[6 7 8]
Explanation:
The number `5` is broadcasted across all elements of the array `[1, 2, 3]`, and the addition
happens element-wise.
48. Module: M2-R5: Web Designing & Publishing
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
home-2741413_960_720.png
Examples of Broadcasting
48
❑ Broadcasting works when NumPy can match dimensions or "expand" the smaller array to the larger
one. This works for operations like addition, subtraction, multiplication, and more.
Example :
import numpy as np
a = np.array([[1,2,3,4],[2,4,5,6],[10,20,39,3]])
b = np.array([2,4,6,8])
print("nprinting array a..")
print(a)
print("nprinting array b..")
print(b)
print("nAdding arrays a and b ..")
c = a + b;
print(c)
49. Module: M2-R5: Web Designing & Publishing
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
home-2741413_960_720.png
NumPy Array Iteration
49
❑ NumPy provides an iterator object, i.e., nditer which can be used to iterate over the
given array using python standard Iterator interface.
Example:
import numpy as np
a = np.array([[1,2,3,4],[2,4,5,6],[10,20,39,3]])
print("Printing array:")
print(a);
print("Iterating over the array:")
for x in np.nditer(a):
print(x,end=' ')
50. Module: M2-R5: Web Designing & Publishing
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
home-2741413_960_720.png
NumPy Bitwise Operators
50
SN Operator Description
1 bitwise_and
It is used to calculate the bitwise and operation between the corresponding array
elements.
2 bitwise_or
It is used to calculate the bitwise or operation between the corresponding array
elements.
3 invert It is used to calculate the bitwise not the operation of the array elements.
4 left_shift It is used to shift the bits of the binary representation of the elements to the left.
5 right_shift It is used to shift the bits of the binary representation of the elements to the right.
51. Module: M2-R5: Web Designing & Publishing
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
home-2741413_960_720.png
Example
51
import numpy as np
a = np.array([5, 7, 10, 12]) # Binary: 101, 111, 1010, 1100
b = np.array([3, 6, 12, 15]) # Binary: 011, 110, 1100, 1111
# Bitwise AND
and_result = np.bitwise_and(a, b)
print("Bitwise AND:", and_result)
# Bitwise OR
or_result = np.bitwise_or(a, b)
print("Bitwise OR:", or_result)
# Bitwise NOT on array 'b'
not_result_b = np.invert(b)
print("Bitwise NOT on b:", not_result_b)
print("binary representation of a:",bin(a))
print("binary representation of b:",bin(b))
52. Module: M2-R5: Web Designing & Publishing
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
home-2741413_960_720.png
Output
52
Output:
binary representation of a: 101, 111, 1010, 1100
binary representation of b: 011, 110, 1100, 1111
Bitwise AND: [ 1 6 8 12]
Bitwise OR: [ 7 7 14 15]
Bitwise NOT on b: [-4 -7 -13 -16]
53. Module: M2-R5: Web Designing & Publishing
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
home-2741413_960_720.png
NumPy Sorting and Searching
53
❑ Numpy provides a variety of functions for sorting and searching. There are various
sorting algorithms like quicksort, merge sort and heapsort which is implemented using
the numpy.sort() function.
Syntax:
numpy.sort(a, axis, kind, order)
❑ It accepts the following parameters.
Input
It represents the input array which is to be sorted.
axis
It represents the axis along which the array is to be sorted. If the axis is not mentioned,
then the sorting is done along the last available axis.
54. Module: M2-R5: Web Designing & Publishing
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
home-2741413_960_720.png
Continue…
54
❑ Kind
It represents the type of sorting algorithm which is to be used while sorting. The default
is quick sort.
❑ Order
It represents the filed according to which the array is to be sorted in the case if the array
contains the fields.
55. Module: M2-R5: Web Designing & Publishing
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
home-2741413_960_720.png
Example
55
import numpy as np
a = np.array([[10,2,3],[4,5,6],[7,8,9]])
print("Sorting along the columns:")
print(np.sort(a))
print("Sorting along the rows:")
print(np.sort(a, 0))
Output:
Sorting along the columns:
[[ 2 3 10]
[ 4 5 6]
[ 7 8 9]]
Sorting along the rows:
[[ 4 2 3]
[ 7 5 6]
[10 8 9]]
56. Module: M2-R5: Web Designing & Publishing
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
home-2741413_960_720.png
Continue…
56
❑ NumPy provides several functions for searching for specific elements or indices in an
array.
❑ numpy.nonzero() :This function is used to find the location of the non-zero elements
from the array.
Example
import numpy as np
b = np.array([12, 90, 380, 12, 211])
print("printing original array",b)
print("printing location of the non-zero elements")
print(b.nonzero())
Output:
printing original array [ 12 90 380 12 211]
printing location of the non-zero elements (array([0, 1, 2, 3, 4]),)
57. Module: M2-R5: Web Designing & Publishing
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
home-2741413_960_720.png
Continue…
57
❑ numpy.where(): This function is used to return the indices of all the elements which
satisfies a particular condition.
Example
arr = np.array([5, 1, 9, 3, 7])
# Find the indices where the element is greater than 5
indices = np.where(arr > 5)
print("Indices where elements are greater than 5:", indices)
# Use the indices to get the elements
elements = arr[indices]
print("Elements greater than 5:", elements)
58. Module: M2-R5: Web Designing & Publishing
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
home-2741413_960_720.png
Output
58
Indices where elements are greater than 5: (array([2, 4]),)
Elements greater than 5: [9 7]
59. Module: M2-R5: Web Designing & Publishing
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
home-2741413_960_720.png
Assignment
59
❑ Write a Python script to create a NumPy ndarray from a list of lists. Then, reshape the
ndarray into a different shape and print both the original and reshaped arrays.
❑ Create a 3x3 NumPy array with random integers. Perform slicing operations to extract
specific rows and columns.
❑ Generate a 4x4 array of random numbers. Write functions to find the maximum,
minimum, sum, square root, and standard deviation of the array elements.
❑ Create two 1-dimensional NumPy arrays and concatenate them into a single array.
❑ Write a Python program to create a NumPy array with random integers. Sort the array
in ascending order and then search for a specific element within the array.
60. Module: M2-R5: Web Designing & Publishing
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
home-2741413_960_720.png
60
Thank You