Lesson 06 Mathematical Computing Using NumPy
Lesson 06 Mathematical Computing Using NumPy
List
Collection of values
Though you can change individual values in a list, you cannot apply a mathematical operation over the entire list.
Error
Why NumPy?
Numerical Python (NumPy) supports multidimensional arrays over which you can easily apply mathematical operations.
Numpy
26 43 52
Import NumPy
Output
NumPy: Overview
The ndarray in Python is used as the primary container to exchange data between algorithms.
Algorithm
[1, 2, 1]
Question/Problem
[[ 1, 0, 0],
[ 0, 1, 2]]
Sharing
Data
([[ 2, 8, 0, 6],
Algorithm [ 4, 5, 1, 1],
[ 8, 9, 3, 6]])
ndarray
Write Program
Algorithm
Types of Arrays
array([[[ 0, 1, 2],
1 axis [ 3, 4, 5],
array([5, 7,9]) array([[ 0, 1, 2], 2 axes
rank 1 [ 6, 7, 8]],
[ 5, 6, 7]]) rank 2
Length = 3 [[ 9, 10, 11],
3 axes
[12, 13, 14],
rank 3
Length = 3 [15, 16, 17]],
Numpy array class is ndarray, also referred to as numpy.ndarray. The attributes of ndarray are:
This refers to the number of axes (dimensions) of the array. It is also called the rank of the
ndarray.ndim array.
ndarray.shape
ndarray.size
Two axes or 2D array Three axes or 3D array
ndarray.dtype
Concept Example
Class and Attributes of ndarray: .ndim
ndarray.shape
ndarray.size
ndarray.dtype
Concept Example
Class and Attributes of ndarray: .shape
Numpy array class is ndarray, also referred to as numpy.ndarray. The attributes of ndarray are:
This consists of a tuple of integers showing the size of the array in each dimension. The
ndarray.ndim length of the shape tuple is the rank or ndim.
ndarray.shape
ndarray.dtype
Concept Example
Class and Attributes of ndarray: .shape
Numpy’s array class is “ndarray,” also referred to as “numpy.ndarray.” The attributes of ndarray are:
The shape tuple of both the arrays indicate their size along each dimension.
ndarray.ndim
ndarray.shape
ndarray.size
ndarray.dtype
Concept Example
Class and Attributes of ndarray: .size
Numpy’s array class is “ndarray,” also referred to as “numpy.ndarray.” The attributes of ndarray are:
It gives the total number of elements in the array. It is equal to the product of the elements
ndarray.ndim of the shape tuple.
ndarray.shape
ndarray.dtype
Concept Example
Class and Attributes of ndarray: .size
Numpy’s array class is “ndarray,” also referred to as “numpy.ndarray.” The attributes of ndarray are:
Look at the examples to see how shape tuples of the arrays are used to calculate their size.
ndarray.ndim
ndarray.shape
ndarray.size
ndarray.dtype
Concept Example
Class and Attributes of ndarray: .dtype
Numpy’s array class is “ndarray,” also referred to as “numpy.ndarray.” The attributes of ndarray are:
It’s an object that describes the type of the elements in the array. It can be created or
ndarray.ndim specified using Python.
ndarray.shape
ndarray.dtype
Concept Example
Class and Attributes of ndarray: .dtype
Numpy’s array class is “ndarray,” also referred to as “numpy.ndarray.” The attributes of ndarray are:
Both the arrays are of string data type (dtype) and the longest string is of length 7, which is
ndarray.ndim Houston.
ndarray.shape
ndarray.size
ndarray.dtype
Concept Example
Operations
Basic Operations
Using the following operands, you can easily apply various mathematical, logical, and comparison operations
on an array.
NumPy uses the indices of the elements in each array to carry out basic operations. In this case, where we are
looking at a dataset of four cyclists during two trials, vector addition of the arrays gives the required output.
First trial
Second trial
Total distance
10 15 17 26 + 12 11 21 24 = 22 26 38 50
0 1 2 3 0 1 2 3
Index Index
Vector addition
Executing Basic Operations in NumPy Array
Objective: Create a NumPy array and perform the following basic operations:
- Mathematical operations
- Comparison operations
- Logical operations
Output
Output
Unassisted Practice: Operations Using NumPy Array
Output
Output
Accessing Array Elements: Indexing
You can access an entire row of an array by referencing its axis index.
10 15 17 26
2 rows
Shape of the array 12 11 21 24
4 columns
Use “:” to
10 15 17 26
select all rows 12 11 21 24
Use the iteration method to go through each data element present in the dataset.
Boolean arrays are useful when you need to select a dataset according to a set criteria.
Here, the original dataset contains test scores of two students. A Boolean array is used
to choose only the scores that are above a given value.
Test scores
Student 1 83 71 57 63 83 71 57 63
Student 2 54 68 81 45 54 68 81 45
Test score > 60
Test 1 Test 2 Test 3 Test 4
When working with arrays, data is copied into new arrays only in some cases.
Following are the three possible scenarios:
In this method, a variable is directly assigned the value of another variable. No new copy is made.
Simple Assignments
Original dataset
Assigned dataset
Simple Assignments
Original dataset
Original dataset
Deep Copy
changed
Copy and Views
Copy is also called deep copy because it entirely copies the original dataset. Any change in the copy
will not affect the original dataset.
Simple Assignments
Shows copy and original
object are different
Original dataset
Deep Copy retained
Demonstrate the Use of Copy and Views
Objective: Demonstrate how the following copies and views are generated from a memory location:
- Simple Assignment
- View or Shallow Copy
- Deep Copy
NumPy provides useful mathematical functions called universal functions. These functions operate element-wise on
an array, producing another array as output. Some of these functions are:
sqrt function provides the square sqrt cos function gives cosine values for all
root of every element in the array. elements in the array.
cos
floor
floor function returns the largest exp exp function performs exponentiation
integer value of every element in the
on every element in the array.
array.
ufunc: Examples
Import pi*
Trigonometric functions
1 2 3
1 2 3 4 5 6 7 8 9 4 5 6
7 8 9
1 2 3
4 5 6
7 8 9
Flatten
Split Resize
Shape
Manipulation
Stack Reshape
Manipulate the Shape of an Array
Objective: Use common manipulation functions like ravel, reshape, resize, hsplit, and hstack to manipulate
the shape of a NumPy array.
Access: To execute the practice, follow these steps:
• Go to the PRACTICE LABS tab on your LMS
• Click the START LAB button
• Click the LAUNCH LAB button to start the lab
Broadcasting
NumPy uses broadcasting to carry out arithmetic operations between arrays of different shapes. In this method,
NumPy automatically broadcasts the smaller array over the larger array.
array_a
2 3 5 8
Element-wise
multiplication
0.3 0.3 0.3 0.3
array_b
array_a
2 3 5 8
Broadcasting
0.3
scalar_c
If the shape doesn’t match with array_a, NumPy doesn’t have to create copies of scalar values.
Instead, broadcast scalar value over the entire array to find the product.
Broadcasting: Constraints
Though broadcasting can help carry out mathematical operations between different-shaped arrays, they are subject
to certain constraints as listed below:
Let’s look at an example to see how broadcasting works to calculate the number of working hours of a worker per
day in a certain week.
Element-wise operation
Hourly wage
NumPy can carry out linear algebraic functions as well. The transpose() function can help you interchange rows as
columns, and vice-versa.
transpose()
Axis 1 Axis 1
83 71 57 63
54 68 81 45
Axis 0
Axis 0
Linear Algebra: Inverse and Trace Functions
Using NumPy, you can also find the inverse of an array and add its diagonal data elements.
np.linalg.inv()
np.trace()
A NumPy ndarray can hold only a single data type, which makes it homogenous. NumPy supports integers, floats, Booleans,
and even complex numbers. Of all the options provided, only the array containing complex numbers is homogenous. All the
other options contain more than one data type.
Knowledge
Check Which function is most useful to convert a multidimensional array into a one-dimensional
array?
2
a. ravel()
b. reshape()
a. ravel()
b. reshape()
The function ravel() is used to convert a multidimensional array into a one-dimensional array. Though reshape() also functions
in a similar way, it creates a new array instead of transforming the input array.
Knowledge
Check
The np.trace() method gives the sum of _____.
3
The trace() function is used to find the sum of the diagonal elements in an array. It is carried out in an incremental order of the
indices. Therefore, it can only add diagonal values from left to right and not vice-versa.
Knowledge
Check
The function np.transpose() when applied on a one-dimensional array gives _____.
4
a. a reverse array
c. an inverse array
a. a reverse array
c. an inverse array
Transposing a one-dimensional array does not change it in any way. It returns an unchanged view of the original array.
Country GDP