Unit 2
Unit 2
What is NumPy?
NumPy is a Python library used for working with arrays.
It also has functions for working in domain of linear algebra, fourier transform,
and matrices.
NumPy was created in 2005 by Travis Oliphant. It is an open source project and
you can use it freely.
NumPy aims to provide an array object that is up to 50x faster than traditional
Python lists.
Arrays are very frequently used in data science, where speed and resources are
very important.
This is the main reason why NumPy is faster than lists. Also it is optimized to
work with latest CPU architectures.
UNIT-2 NUMPY
Installation of NumPy
If you have Python and PIP already installed on a system, then installation of
NumPy is very easy.
Import NumPy
Once NumPy is installed, import it in your applications by adding
the import keyword:
import numpy
To create an ndarray, we can pass a list, tuple or any array-like object into
the array() method, and it will be converted into an ndarray:
Dimensions in Arrays
A dimension in arrays is one level of array depth (nested arrays).
UNIT-2 NUMPY
0-D Arrays
0-D arrays, or Scalars, are the elements in an array. Each value in an array is a
0-D array.
1-D Arrays
An array that has 0-D arrays as its elements is called uni-dimensional or 1-D
array.
2-D Arrays
An array that has 1-D arrays as its elements is called a 2-D array.
3-D arrays
An array that has 2-D arrays (matrices) as its elements is called 3-D array.
When the array is created, you can define the number of dimensions by using
the ndmin argument.
The indexes in NumPy arrays start with 0, meaning that the first element has
index 0, and the second has index 1 etc.
UNIT-2 NUMPY
Think of 2-D arrays like a table with rows and columns, where the dimension
represents the row and the index represents the column.
Slicing arrays
Slicing in python means taking elements from one given index to another given
index.
STEP
Use the step value to determine the step of the slicing:
strings - used to represent text data, the text is given under quote
marks. e.g. "ABCD"
integer - used to represent integer numbers. e.g. -1, -2, -3
UNIT-2 NUMPY
Below is a list of all data types in NumPy and the characters used to represent
them.
i - integer
b - boolean
u - unsigned integer
f - float
c - complex float
m - timedelta
M - datetime
O - object
S - string
U - unicode string
V - fixed chunk of memory for other type ( void )
The astype() function creates a copy of the array, and allows you to specify the
data type as a parameter.
The data type can be specified using a string, like 'f' for float, 'i' for integer
etc. or you can use the data type directly like float for float and int for
integer.
The copy owns the data and any changes made to the copy will not affect
original array, and any changes made to the original array will not affect the
copy.
The view does not own the data and any changes made to the view will affect
the original array, and any changes made to the original array will affect the
view.
COPY:
Example
import numpy as np
print(arr)
print(x)
VIEW:
UNIT-2 NUMPY
Example
import numpy as np
print(arr)
print(x)
Every NumPy array has the attribute base that returns None if the array owns the
data.
Shape of an Array
The shape of an array is the number of elements in each dimension.
Reshaping arrays
UNIT-2 NUMPY
Unknown Dimension
You are allowed to have one "unknown" dimension.
Meaning that you do not have to specify an exact number for one of the
dimensions in the reshape method.
Pass -1 as the value, and NumPy will calculate this number for you.
Iterating Arrays
Iterating means going through elements one by one.
We can concatenate two 1-D arrays along the second axis which would result in
putting them one over the other, ie. stacking.
We pass a sequence of arrays that we want to join to the stack() method along
with the axis. If axis is not explicitly passed it is taken as 0.
Joining merges multiple arrays into one and Splitting breaks one array into
multiple.
We use array_split() for splitting arrays, we pass it the array we want to split
and the number of splits.
UNIT-2 NUMPY
If you split an array into 3 arrays, you can access them from the result just like
any array element:
Use the array_split() method, pass in the array you want to split and the
number of splits you want to do.
Searching Arrays
You can search an array for a certain value, and return the indexes that get a
match.
Search Sorted
There is a method called searchsorted() which performs a binary search in the
array, and returns the index where the specified value would be inserted to
maintain the search order.
Sorting Arrays
Sorting means putting elements in an ordered sequence.
UNIT-2 NUMPY
The NumPy ndarray object has a function called sort(), that will sort a specified
array.
It is used to calculate
the bitwise or
2 bitwise_or operation between the
corresponding array
elements.
It is used to calculate
the bitwise not the
3 invert
operation of the array
elements.
bitwise_and Operation
UNIT-2 NUMPY
The NumPy provides the bitwise_and() function which is used to calculate the bitwise_and
operation of the two operands.
The bitwise and operation is performed on the corresponding bits of the binary representation
of the operands. If both the corresponding bit in the operands is set to 1, then only the
resultant bit in the AND result will be set to 1 otherwise it will be set to 0.
bitwise_or Operator
The NumPy provides the bitwise_or() function which is used to calculate the bitwise or
operation of the two operands.
The bitwise or operation is performed on the corresponding bits of the binary representation
of the operands. If one of the corresponding bit in the operands is set to 1 then the resultant
bit in the OR result will be set to 1; otherwise it will be set to 0.
Invert operation
It is used to calculate the bitwise not the operation of the given operand. The 2's complement
is returned if the signed integer is passed in the function.
It shifts the bits in the binary representation of the operand to the left by the specified
position. An equal number of 0s are appended from the right.
Trigonometric functions
Numpy contains the trigonometric functions which are used to calculate the sine, cosine, and
tangent of the different angles in radian.
The sin, cos, and tan functions return the trigonometric ratio for the specified angles.
UNIT-2 NUMPY
On the other hand, arcsin(), arccos(), and arctan() functions return the trigonometric inverse
of the specified angles.
The numpy.degrees() function can be used to verify the result of these trigonometric
functions.
Rounding Functions
The numpy provides various functions that can be used to truncate the value of a decimal
float number rounded to a particular precision of decimal numbers. Let's discuss the rounding
functions.
numpy.around(num, decimals)
Parameter List
1 num It is the input number.
It is the number of
decimals which to
which the number is to
be rounded. The
2 decimals
default value is 0. If
this value is negative,
then the decimal will
be moved to the left.
numpy.ptp() function
The name of the function numpy.ptp() is derived from the name peak-to-peak. It is used to
return the range of values along an axis.
numpy.percentile() function
The syntax to use the function is given below.
numpy.percentile(input, q, axis)
The numpy.average() function is used to find the weighted average along the axis of the multi-
dimensional arrays where their weights are given in another array.
numpy.matlib.empty() function
This function is used to return a new matrix with the uninitialized entries. The syntax to use
this function is given below.
numpy.matlib.zeros() function
This function is used to create the matrix where the entries are initialized to zero.
numpy.matlib.ones() function
This function returns a matrix with all the elements initialized to 1.
numpy.matlib.eye() function
This function returns a matrix with the diagonal elements initialized to 1 and zero elsewhere.
The syntax to use this function is given below.
1. numpy.matlib.eye(n, m, k, dtype)
It accepts the following parameters.
numpy.matlib.identity() function
This function is used to return an identity matrix of the given size. An identity matrix is the one
with diagonal elements initializes to 1 and all other elements to zero.
numpy.matlib.rand() function
This function is used to generate a matrix where all the entries are initialized with random
values.
UNIT-2 NUMPY
It is used to calculate
1 dot() the dot product of two
arrays.
It is used to calculate
2 vdot() the dot product of two
vectors.
It is used to calculate
3 inner() the inner product of
two arrays.
It is used to calculate
the matrix
4 matmul()
multiplication of two
arrays.
It is used to calculate
5 det() the determinant of a
matrix.
It is used to calculate
7 inv() the multiplicative
inverse of the matrix.
numpy.dot() function
This function is used to return the dot product of the two matrices. It is similar to the matrix
multiplication.
UNIT-2 NUMPY
umpy.vdot() function
This function is used to calculate the dot product of two vectors. It can be defined as the sum
of the product of corresponding elements of multi-dimensional arrays.
numpy.inner() function
This function returns the sum of the product of inner elements of the one-dimensional array.
For n-dimensional arrays, it returns the sum of the product of elements over the last axis.
numpy.matmul() function
It is used to return the multiplication of the two matrices. It gives an error if the shape of both
matrices is not aligned for multiplication.
numpy determinant
The determinant of the matrix can be calculated using the diagonal elements. The
determinant of following 2 X 2 matrix
A B
C D
numpy.linalg.solve() function
This function is used to solve a quadratic equation where values can be given in the form of
the matrix.
numpy.linalg.inv() function
This function is used to calculate the multiplicative inverse of the input matrix.
NumPy Broadcasting
Broadcasting in NumPy refers to the ability of performing operations on arrays
with different shapes by automatically expanding the smaller array's shape to
match the larger array's shape. This is useful when performing arithmetic
operations or applying functions to arrays of different dimensions.
UNIT-2 NUMPY
Rules of Broadcasting
For broadcasting to work, the following rules must be satisfied −
For instance, consider two arrays with shapes (3, 4) and (4,). The broadcasting
rules will align the shapes as follows −
Pad the smaller array's shape: The smaller array shape (4,) is padded to (1, 4).
Align dimensions: The shapes (3, 4) and (1, 4) are aligned as (3, 4) and (3, 4)
respectively.
Perform element-wise operation: The operation is applied to the aligned shapes.
This process eliminates the need for manually reshaping arrays before
performing operations.
UNIT-2 NUMPY
This process involves stretching the smaller array to match the shape of the
larger one, enabling operations to be performed smoothly.