Data Science With Python Lesson 05 Mathematical Computing With Python NumPy
Data Science With Python Lesson 05 Mathematical Computing With Python NumPy
List
Collection of values
You can change individual values in a list, but 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]],
The code here is buggy. You must correct its sequence to debug it.
4
Activity: Sequence it Right!
4
Creating and Printing an ndarray
Numpy’s 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
Classes and Attributes of ndarray: .ndim
ndarray.shape
ndarray.size
ndarray.dtype
Concept Example
Classes and Attributes of ndarray: .shape
Numpy’s 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
Classes 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
Classes 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
Classes 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 the shape tuples of the arrays are used to calculate their
ndarray.ndim size.
ndarray.shape
ndarray.size
ndarray.dtype
Concept Example
Classes 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
Classes 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
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
Select any two elements from the array to see how the statement required to slice the range changes.
5 8 10 21
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 set criteria.
True False
Indexing with Boolean Arrays
Here, the original dataset contains test scores of two students. You can use a Boolean array 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
View/Shallow Copy
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
Universal Functions (ufunc)
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
integer value of every element in the
exponentiation on each element.
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
Shape Manipulation: Example
You can use certain functions to manipulate the shape of an array to do the following:
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 value.
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.
Key Takeaways