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 stands for Numerical Python.
Why Use NumPy?
In Python we have lists that serve the purpose of arrays, but they are slow to
process.
NumPy aims to provide an array object that is up to 50x faster than traditional
Python lists.
The array object in NumPy is called ndarray, it provides a lot of supporting
functions that make working with ndarray very easy.
Arrays are very frequently used in data science, where speed and resources are
very important.
Data Science: is a branch of computer science where we study how to store,
use and analyze data for deriving information from it.
Why is NumPy Faster Than Lists?
NumPy arrays are stored at one continuous place in memory unlike lists, so
processes can access and manipulate them very efficiently.
This behavior is called locality of reference in computer science.
This is the main reason why NumPy is faster than lists. Also it is optimized to
work with latest CPU architectures.
Which Language is NumPy written in?
NumPy is a Python library and is written partially in Python, but most of the
parts that require fast computation are written in C or C++.
Where is the NumPy Codebase?
The source code for NumPy is located at this github
repository https://github.com/numpy/numpy
github: enables many people to work on the same codebase.
Installation of NumPy
If you have Python and PIP already installed on a system, then installation of
NumPy is very easy.
Install it using this command:
C:\Users\Your Name>pip install numpy
If this command fails, then use a python distribution that already has NumPy
installed like, Anaconda, Spyder etc.
Import NumPy
Once NumPy is installed, import it in your applications by adding
the import keyword:
import numpy
Now NumPy is imported and ready to use.
Example
import numpy
arr = numpy.array([1, 2, 3, 4, 5])
print(arr)
NumPy as np
NumPy is usually imported under the np alias.
alias: In Python alias are an alternate name for referring to the same thing.
Create an alias with the as keyword while importing:
import numpy as np
Now the NumPy package can be referred to as np instead of numpy.
Example
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)
Checking NumPy Version
The version string is stored under __version__ attribute.
Example
import numpy as np
print(np.__version__)
NumPy Creating Arrays
Create a NumPy ndarray Object
NumPy is used to work with arrays. The array object in NumPy is called ndarray.
We can create a NumPy ndarray object by using the array() function.
Example
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)
print(type(arr))
type(): This built-in Python function tells us the type of the object passed to it.
Like in above code it shows that arr is numpy.ndarray type.
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:
Example
Use a tuple to create a NumPy array:
import numpy as np
arr = np.array((1, 2, 3, 4, 5))
print(arr)
Dimensions in Arrays
A dimension in arrays is one level of array depth (nested arrays).
nested array: are arrays that have arrays as their elements.
0-D Arrays
0-D arrays, or Scalars, are the elements in an array. Each value in an array is a
0-D array.
Example
Create a 0-D array with value 42
import numpy as np
arr = np.array(42)
print(arr)
1-D Arrays
An array that has 0-D arrays as its elements is called uni-dimensional or 1-D
array.
These are the most common and basic arrays.
Example
Create a 1-D array containing the values 1,2,3,4,5:
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)
2-D Arrays
An array that has 1-D arrays as its elements is called a 2-D array.
These are often used to represent matrix or 2nd order tensors.
NumPy has a whole sub module dedicated towards matrix operations
called numpy.mat
Example
Create a 2-D array containing two arrays with the values 1,2,3 and 4,5,6:
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr)
3-D arrays
An array that has 2-D arrays (matrices) as its elements is called 3-D array.
These are often used to represent a 3rd order tensor.
Example
Create a 3-D array with two 2-D arrays, both containing two arrays with the
values 1,2,3 and 4,5,6:
import numpy as np
arr = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])
print(arr)
Check Number of Dimensions?
NumPy Arrays provides the ndim attribute that returns an integer that tells us
how many dimensions the array have.
Example
Check how many dimensions the arrays have:
import numpy as np
a = np.array(42)
b = np.array([1, 2, 3, 4, 5])
c = np.array([[1, 2, 3], [4, 5, 6]])
d = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])
print(a.ndim)
print(b.ndim)
print(c.ndim)
print(d.ndim)
Higher Dimensional Arrays
An array can have any number of dimensions.
When the array is created, you can define the number of dimensions by using
the ndmin argument.
Example
Create an array with 5 dimensions and verify that it has 5 dimensions:
import numpy as np
arr = np.array([1, 2, 3, 4], ndmin=5)
print(arr)
print('number of dimensions :', arr.ndim)
In this array the innermost dimension (5th dim) has 4 elements, the 4th dim
has 1 element that is the vector, the 3rd dim has 1 element that is the matrix
with the vector, the 2nd dim has 1 element that is 3D array and 1st dim has 1
element that is a 4D array.
NumPy Array Indexing
Access Array Elements
Array indexing is the same as accessing an array element.
You can access an array element by referring to its index number.
The indexes in NumPy arrays start with 0, meaning that the first element has
index 0, and the second has index 1 etc.
Example Get the first element from the following array:
import numpy as np
arr = np.array([1, 2, 3, 4])
print(arr[0])
Example Get the second element from the following array.
import numpy as np
arr = np.array([1, 2, 3, 4])
print(arr[1])
Example Get third and fourth elements from the following array and
add them.
import numpy as np
arr = np.array([1, 2, 3, 4])
print(arr[2] + arr[3])
Access 2-D Arrays
To access elements from 2-D arrays we can use comma separated integers
representing the dimension and the index of the element.
Think of 2-D arrays like a table with rows and columns, where the dimension
represents the row and the index represents the column.
Example
Access the element on the first row, second column:
import numpy as np
arr = np.array([[1,2,3,4,5], [6,7,8,9,10]])
print('2nd element on 1st row: ', arr[0, 1])
Example
Access the element on the 2nd row, 5th column:
import numpy as np
arr = np.array([[1,2,3,4,5], [6,7,8,9,10]])
print('5th element on 2nd row: ', arr[1, 4])
Access 3-D Arrays
To access elements from 3-D arrays we can use comma separated integers
representing the dimensions and the index of the element.
Example
Access the third element of the second array of the first array:
import numpy as np
arr = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
print(arr[0, 1, 2])
Example Explained
arr[0, 1, 2] prints the value 6.
And this is why:
The first number represents the first dimension, which contains two arrays:
[[1, 2, 3], [4, 5, 6]]
and:
[[7, 8, 9], [10, 11, 12]]
Since we selected 0, we are left with the first array:
[[1, 2, 3], [4, 5, 6]]
The second number represents the second dimension, which also contains two
arrays:
[1, 2, 3]
and:
[4, 5, 6]
Since we selected 1, we are left with the second array:
[4, 5, 6]
The third number represents the third dimension, which contains three values:
4
5
6
Since we selected 2, we end up with the third value:
6
Negative Indexing
Use negative indexing to access an array from the end.
Example Print the last element from the 2nd dim:
import numpy as np
arr = np.array([[1,2,3,4,5], [6,7,8,9,10]])
print('Last element from 2nd dim: ', arr[1, -1])
NumPy Array Slicing: Slicing arrays
Slicing in python means taking elements from one given index to another given
index.
We pass slice instead of index like this: [start:end].
We can also define the step, like this: [start:end:step].
If we don't pass start its considered 0
If we don't pass end its considered length of array in that dimension
If we don't pass step its considered 1
Example
Slice elements from index 1 to index 5 from the following array:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7])
print(arr[1:5])
Note: The result includes the start index, but excludes the end index.
Example
Slice elements from index 4 to the end of the array:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7])
print(arr[4:])
Example
Slice elements from the beginning to index 4 (not included):
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7])
print(arr[:4])
Negative Slicing
Use the minus operator to refer to an index from the end:
Example
Slice from the index 3 from the end to index 1 from the end:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7])
print(arr[-3:-1])
STEP
Use the step value to determine the step of the slicing:
Example
Return every other element from index 1 to index 5:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7])
print(arr[1:5:2])
Example
Return every other element from the entire array:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7])
print(arr[::2])
Slicing 2-D Arrays
Example
From the second element, slice elements from index 1 to index 4 (not included):
import numpy as np
arr = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
print(arr[1, 1:4])
Note: Remember that second element has index 1.
Example
From both elements, return index 2:
import numpy as np
arr = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
print(arr[0:2, 2])
Example
From both elements, slice index 1 to index 4 (not included), this will return a
2-D array:
import numpy as np
arr = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
print(arr[0:2, 1:4])
NumPy Array Shape
Shape of an Array
The shape of an array is the number of elements in each dimension.
Get the Shape of an Array
NumPy arrays have an attribute called shape that returns a tuple with each index
having the number of corresponding elements.
Example
Print the shape of a 2-D array:
import numpy as np
arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
print(arr.shape)
The example above returns (2, 4), which means that the array has 2
dimensions, where the first dimension has 2 elements and the second has 4.
Example
Create an array with 5 dimensions using ndmin using a vector with values 1,2,3,4
and verify that last dimension has value 4:
import numpy as np
arr = np.array([1, 2, 3, 4], ndmin=5)
print(arr)
print('shape of array :', arr.shape)
Output: [[[[[1 2 3 4]]]]]
shape of array : (1, 1, 1, 1, 4)
What does the shape tuple represent?
Integers at every index tells about the number of elements the corresponding
dimension has.
In the example above at index-4 we have value 4, so we can say that 5th ( 4 +
1 th) dimension has 4 elements.
NumPy Array Reshaping
Reshaping arrays
Reshaping means changing the shape of an array.
The shape of an array is the number of elements in each dimension.
By reshaping we can add or remove dimensions or change number of elements
in each dimension.
Reshape From 1-D to 2-D
ExampleGet your own Python Server
Convert the following 1-D array with 12 elements into a 2-D array.
The outermost dimension will have 4 arrays, each with 3 elements:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
newarr = arr.reshape(4, 3)
print(newarr)
NumPy Array Iterating
Iterating Arrays
Iterating means going through elements one by one.
As we deal with multi-dimensional arrays in numpy, we can do this using
basic for loop of python.
If we iterate on a 1-D array it will go through each element one by one.
Example
Iterate on the elements of the following 1-D array:
import numpy as np
arr = np.array([1, 2, 3])
for x in arr:
print(x)
Iterating 2-D Arrays
In a 2-D array it will go through all the rows.
Example
Iterate on the elements of the following 2-D array:
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
for x in arr:
print(x)
If we iterate on a n-D array it will go through n-1th dimension one by one.
To return the actual values, the scalars, we have to iterate the arrays in each
dimension.
Example
Iterate on each scalar element of the 2-D array:
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
for x in arr:
for y in x:
print(y)
Iterating 3-D Arrays
In a 3-D array it will go through all the 2-D arrays.
Example
Iterate on the elements of the following 3-D array:
import numpy as np
arr = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
for x in arr:
print(x)
To return the actual values, the scalars, we have to iterate the arrays in each
dimension.
Example
Iterate down to the scalars:
import numpy as np
arr = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
for x in arr:
for y in x:
for z in y:
print(z)
NumPy Trigonometric Functions
NumPy provides the ufuncs sin(), cos() and tan() that take values in radians and
produce the corresponding sin, cos and tan values.
Here's a list of commonly used trigonometric functions in NumPy.
Trigonometric Function Computes (in radians)
sin() the sine of an angle
cos() cosine of an angle
tan() tangent of an angle
arcsin() the inverse sine
arccos() the inverse cosine
arctan() the inverse tangent
degrees() converts an angle in radians to degrees
radians() converts an angle in degrees to radians
Examples.
import numpy as np
# array of angles in radians
angles = np.array([0, 1, 2])
print("Angles:", angles)
# compute the sine of the angles
sine_values = np.sin(angles)
print("Sine values:", sine_values)
# compute the inverse sine of the angles
inverse_sine = np.arcsin(angles)
print("Inverse Sine values:", inverse_sine)
Output
Angles: [0 1 2]
Sine values: [0. 0.84147098 0.90929743]
Inverse Sine values: [0. 1.57079633 nan]
In this example, the sin() and arcsin() functions calculate the sine and inverse
sine values, respectively, for each element in the angles array.
The resulting values are in radians.
Now let's see the examples for degrees() and radians().
import numpy as np
# define an angle in radians
angle = 1.57079633
print("Initial angle in radian:", angle)
# convert the angle to degrees
angle_degree = np.degrees(angle)
print("Angle in degrees:", angle_degree)
# convert the angle back to radians
angle_radian = np.radians(angle_degree)
print("Angle in radians (after conversion):", angle_radian)
Output
Initial angle in radian: 1.57079633
Angle in degrees: 90.0000001836389
Angle in radians (after conversion): 1.57079633
Here, we first initialized an angle in radians. Then we converted it to degrees
using the degrees() function.
Similarly, we used radians() to convert the degrees back to radians.
Example
Find sine value of PI/2:
import numpy as np
x = np.sin(np.pi/2)
print(x)
Example
Find sine values for all of the values in arr:
import numpy as np
arr = np.array([np.pi/2, np.pi/3, np.pi/4, np.pi/5])
x = np.sin(arr)
print(x)
Convert Degrees Into Radians
By default all of the trigonometric functions take radians as parameters but we
can convert radians to degrees and vice versa as well in NumPy.
Note: radians values are pi/180 * degree_values.
Example
Convert all of the values in following array arr to radians:
import numpy as np
arr = np.array([90, 180, 270, 360])
x = np.deg2rad(arr)
print(x)
Radians to Degrees
Example
Convert all of the values in following array arr to degrees:
import numpy as np
print(np.pi)
arr = np.array([np.pi/2, np.pi, 1.5*np.pi, 2*np.pi])
x = np.rad2deg(arr)
print(x)
Arithmetic Functions
NumPy provides a wide range of arithmetic functions to perform on arrays.
Here's a list of various arithmetic functions along with their associated
operators:
Operation Arithmetic Function Operator
Addition add() +
Subtraction subtract() -
Multiplication multiply() *
Division divide() /
Exponentiation power() **
Modulus mod() %
Operations on Numpy Array : Arithmetic Operations:
import numpy
# initializing matrices
x = numpy.array([[1, 2], [4, 5]])
y = numpy.array([[7, 8], [9, 10]])
print ("The element wise addition of matrix is : ")
print (numpy.add(x,y))
print ("The element wise subtraction of matrix is : ")
print (numpy.subtract(x,y))
print ("The element wise multiplication of matrix is : ")
print (numpy.multiply(x,y))
print ("The multiplication of matrix is : ")
print (numpy.dot(x,y))
print ("The element wise division of matrix is : ")
print (numpy.divide(x,y)):')
print(np.divide(arr1, arr2))
Output:
The element wise addition of matrix is :
[[ 8 10]
[13 15]]
The element wise subtraction of matrix is :
[[-6 -6]
[-5 -5]]
The element wise multiplication of matrix is :
[[ 7 16]
[36 50]]
The multiplication of matrix is :
[[25 28]
[73 82]]
The element wise division of matrix is :
[[0.14285714 0.25 ]
[0.44444444 0.5 ]]
numpy.power() This function treats elements in the first input array as the
base and returns it raised to the power of the corresponding element in the
second input array.
# Python code to perform power operation on NumPy array
import numpy as np
arr = np.array([5, 10, 15])
print('First array is:')
print(arr)
print('\nApplying power function:')
print(np.power(arr, 2))
print('\nSecond array is:')
arr1 = np.array([1, 2, 3])
print(arr1)
print('\nApplying power function again:')
print(np.power(arr, arr1))
Output:
First array is:
[ 5 10 15]
Applying power function:
[ 25 100 225]
Second array is:
[1 2 3]
Applying power function again:
[ 5 100 3375]
numpy.mod() This function returns the remainder of division of the
corresponding elements in the input array. The function numpy.remainder()
also produces the same result.
# Python code to perform mod function# on NumPy array
import numpy as np
arr = np.array([5, 15, 20])
arr1 = np.array([2, 5, 9])
print('First array:')
print(arr)
print('\nSecond array:')
print(arr1)
print('\nApplying mod() function:')
print(np.mod(arr, arr1))
print('\nApplying remainder() function:')
print(np.remainder(arr, arr1))
Output:
First array:
[ 5 15 20]
Second array:
[2 5 9]
Applying mod() function:
[1 0 2]
Applying remainder() function:
[1 0 2]
numpy.square() in Python
●
●
●
numpy.square(arr, out = None, ufunc ‘square’) : This mathematical function
helps user to calculate square value of each element in the array. Parameters
:
arr : [array_like] Input array or object
whose elements, we need to square.
Return :
An array with square value of each array.
# Python program explaining # square () function
import numpy as np
arr1 = [1, -3, 15, -466]
print ("Square Value of arr1 : \n", np.square(arr1))
arr2 = [23 ,-56]
print ("\nSquare Value of arr2 : ", np.square(arr2))
Output :
Square Value of arr1 :
[ 1 9 225 217156]
Square Value of arr2 : [ 529 3136]
Uses of Numpy Where (Conditional Operations )
The numpy.where() function is a powerful tool in the NumPy library used for
conditional selection and manipulation of arrays. This function enables you to search,
filter, and apply conditions to elements of an array, returning specific elements based
on the condition provided.
Syntax :numpy.where(condition[, x, y])
Parameters
● condition: A condition that tests elements of the array.
● x (optional): Values from this array will be returned where the condition is True.
● y (optional): Values from this array will be returned where the condition is False.
Returns: If only the condition is provided, numpy.where() will return the indices of
elements where the condition is true.
Basic Usage Without x and y
If only the condition is provided, numpy.where() returns the indices of elements that
meet the condition.
In this example, numpy.where() checks where the condition arr > 20 is true, and returns
the indices [3, 4], meaning the elements at index 3 and 4 (25 and 30) are greater than
20.
import numpy as np
# Create an array
arr = np.array([10, 15, 20, 25, 30])
# Use np.where() to find indices of elements greater than 20
result = np.where(arr > 20)
print(result)
Output:
(array([3, 4]),)
Using numpy.where() with x and y
By providing x and y as arguments, you can use numpy.where() to return different values
depending on whether the condition is true or false.
Here, the numpy.where() function checks the condition arr > 20. For elements that meet
the condition, it returns 1, and for those that don’t, it returns 0. This is a common
technique to apply binary masks in arrays.
import numpy as np
# Create an array
arr = np.array([10, 15, 20, 25, 30])
# Use np.where() to replace values based on condition
# If the value is greater than 20, return 1, otherwise return 0
result = np.where(arr > 20, 1, 0)
print(result)
Output:
[0 0 0 1 1]
Conditional Selection of Elements from Two Arrays
You can also use numpy.where() to choose elements from two different arrays depending
on a condition.
In this example, for elements where the condition arr1 > 20 is true, the corresponding
element from arr1 is chosen. Otherwise, the element from arr2 is selected.
import numpy as np
# Create two arrays
arr1 = np.array([10, 15, 20, 25, 30])
arr2 = np.array([100, 150, 200, 250, 300])
# Use np.where() to select elements from arr1 where the condition is true, and arr2 otherwise
result = np.where(arr1 > 20, arr1, arr2)
print(result)
Output:
[100 150 200 25 30]