In this Python NumPy Tutorial with examples, you will learn what is NumPy? its features, advantages, modules, packages, and how to use NumPy Arrays with sample examples in Python code.
All examples provided in this Python NumPy tutorial are basic, simple, and easy to practice for beginners who are enthusiastic to learn NumPy and advance their careers.
Note: In case you can’t find the NumPy examples you are looking for on this tutorial page, I would recommend using the Search option from the menu bar to find your tutorial and sample example code.
Table of content :
- What is NumPy?
- NumPy – A Replacement for MatLab
- Install Python Numpy Library
- What is ndarray (N-dimensional array)?
- Arrays In NumPy
- NumPy Array Data Type
- Numpy Array Creation
- Access the Array Elements using the Index
- Convert NumPy Array to Python List
- Convert Python List to A NumPy Array
- Numpy Array Properties
- Operations Using in NumPy Tutorial
1. What is NumPy?
The NumPy library is a popular open-source Python library used for scientific computing applications, and it stands for Numerical Python, which is consisting of multidimensional array objects and a collection of routines for processing those arrays. Using NumPy, we can perform mathematical and logical operations. NumPy is a Python package.
The numeric
library is the ancestor of NumPy, which was developed by Jim Hugunin. Another package Numarray
was also developed, having some additional functionalities. NumPy was created in 2005 by Travis Oliphant
. There are many contributors to this open-source project. It contains various features including these important ones:
- A powerful N-dimensional array object
- Sophisticated (broadcasting) functions
- Tools for integrating C/C++ and Fortran code
- Useful linear algebra, Fourier transform, and random number capabilities
2. NumPy – A Replacement for MatLab
NumPy is often used along with packages like SciPy
(Scientific Python) and Mat−plotlib
(plotting library). This combination is widely used as a replacement for MatLab
, a popular platform for technical computing. However, the Python NumPy is considered an alternative to MatLab which is a more modern and complete programming language.
It is open-source, which is an added advantage of NumPy.
3. Install Python NumPy Library
Standard Python distribution doesn’t come bundled with the NumPy module. hence you need to install NumPy using a popular Python package installer, pip
.
# Install NumPy using PIP
pip install numpy
Otherwise, if you are running Python via the Anaconda distribution, you can execute the following command.
# Install NumPy using Conda
conda install numpy
To test whether NumPy module is properly installed, try to import it from Python prompt.
# Import NumPy
import numpy
If it is not installed, the following error message will be displayed.
Traceback (most recent call last):
File "", line 1, in
import numpy
ImportError: No module named 'numpy'
Alternatively, NumPy package is imported using the following syntax
# Import NumPy with alias as np
import numpy as np
4. What is ndarray (N-dimensional array)?
The most important object defined in NumPy is an N-dimensional array type called numpy.ndarray
.
- It describes the collection of items of the same type. Items in the collection can be accessed using a zero-based index.
- Every item in a
ndarray
takes the same size of a block in the memory. Each element inndarray
is an object of the data-type object (calleddtype
). - Any item extracted from the ndarray object (by slicing) is represented by a Python object of one of the array scalar types.
5. Arrays In NumPy Tutorial
NumPy’s main object is the homogeneous multidimensional array.
- It is a table of elements (usually numbers), all of the same type, indexed by a tuple of positive integers.
- In NumPy dimensions are called axes. The number of axes is rank.
- NumPy’s array class is called
ndarray
. It is also known by the aliasarray
.
We can also pass a collection object into the array routine to create the equivalent n-dimensional array. The syntax is given below.
# Syntax to create NumPy array
numpy.array(object, dtype = None, copy = True, order = None, subok = False, ndmin = 0)
The parameters are described in the following table.
Parameter | Description |
---|---|
object | It represents the collection object. It can be a list, tuple, dictionary, set, etc. |
dtype | We can change the data type of the array elements by changing this option to the specified type. The default is none. |
copy | It is optional. By default, it is true which means the object is copied. |
order | There can be 3 possible values assigned to this option. It can be C (column order), R (row order), or A (any) |
subok | The returned array will be base class array by default. We can change this to make the subclasses passes through by setting this option to true. |
ndmin | It represents the minimum dimensions of the resultant array. |
The following examples give a better understanding,
5.1 Create An NumPy Array Using List
To create a NumPy array from the list, use the following syntax.
# Create ndarray
arr = np.array([10,20,30])
print (arr)
# Output :
[10 20 30]
5.2 Create a Multi-Dimensional Array
To create a multi-dimensional array object, use the following syntax.
# Create multi dimensional array
arr = np.array([[10,20,30],[40,50,60]])
print (arr)
# Output :
[[10 20 30]
[40 50 60]]
5.3 Represent The Minimum Dimensions
Use ndmin
param to specify how many minimum dimensions you wanted to create an array with, For example,
# Minimum dimension
arr = np.array([10, 20, 30,40], ndmin = 2)
print (arr)
# Output:
[[10 20 30 40]]
5.4 Change The Data Type
You can also specify the type of the array elements using dtype
param. Specify the name of the data type along with the collection. For example,
#dtype parameter
arr = np.array([10, 20, 30], dtype = complex)
print(arr)
# Output :
[10.+0.j 20.+0.j 30.+0.j]
5.5 Get The Dimensions of Array
The ndim
param of the array should use to find the dimensions of the array. For example,
# Get dimension of the array
arr = np.array([[1, 2, 3, 4], [7, 8, 6, 7], [9, 10, 11, 12]])
print(arr. ndim)
print(arr)
Outputs :
#2
#[[ 1 2 3 4]
# [ 7 8 6 7]
# [ 9 10 11 12]]
5.6 Get The Size of Each Array Element
The itemsize
function is used to get the size of each array item. It returns the number of bytes taken by each array element. For example,
# Finding the size of each item in the array
arr = np.array([10,20,30])
print("Each item contain in bytes :",arr.itemsize)
Outputs:
Each item contain in bytes: 4
5.7 Get The Data Type of Each Array Item
To check the data type of each array item, the dtype
function is used. Consider the following example to check the data type of the array items. For example,
# Finding the data type of each array item
arr = np.array([10,20,30])
print("Each item is of the type", arr.dtype)
# Output:
Each item is of the type int32
5.8 Get the Shape and Size of Array
To get the shape of the array and size of the array, the size
and shape
() function associated with the NumPy array is used. For example,
# Get shape and size of array
arr = np.array([[10,20,30,40],[60,70,80,90]])
print("Array Size:", arr.size)
print("Shape:", arr.shape)
# Output:
Array Size: 8
Shape: (2, 4)
6. NumPy Array Data Types
NumPy supports a much greater variety of numerical types than Python does. The following table shows different scalar data types defined in NumPy tutorial.
Data Type | Description |
bool_ | It represents the boolean value indicating true or false. It is stored as a byte. |
int_ | It is the default type of integer. It is identical to long type in C that contains 64 bit or 32-bit integer. |
intc | It is similar to the C integer (c int) as it represents 32 or 64-bit int. |
intp | It represents the integers that are used for indexing. |
int8 | It is the 8-bit integer identical to a byte. The range of the value is -128 to 127. |
int16 | It is the 2-byte (16-bit) integer. The range is -32768 to 32767. |
int32 | It is the 4-byte (32-bit) integer. The range is -2147483648 to 2147483647. |
int64 | It is the 8-byte (64-bit) integer. The range is -9223372036854775808 to 9223372036854775807. |
uint8 | It is the 1-byte (8-bit) unsigned integer. |
uint16 | It is the 2-byte (16-bit) unsigned integer. |
uint32 | It is the 4-byte (32-bit) unsigned integer. |
uint64 | It is the 8 bytes (64-bit) unsigned integer. |
float_ | It is identical to float64. |
float16 | It is the half-precision float. 5 bits are reserved for the exponent. 10 bits are reserved for the mantissa, and 1 bit is reserved for the sign. |
float32 | It is a single-precision float. 8 bits are reserved for the exponent, 23 bits are reserved for the mantissa, and 1 bit is reserved for the sign. |
float64 | It is the double-precision float. 11 bits are reserved for the exponent, 52 bits are reserved for the mantissa, 1 bit is used for the sign. |
complex_ | It is identical to complex128. |
complex64 | It is used to represent the complex number where the real and imaginary part shares 32 bits each. |
complex128 | It is used to represent the complex number where the real and imaginary part shares 64 bit each. |
A data type object implements the fixed size of memory corresponding to an array.
6.1 Syntax of Data Type Object
# Syntax of data type
numpy.dtype(object, align, copy)
The constructor allows the following object.
object
: It refers to the object which is to be changed to the data type.
align
: It can be set to any boolean value. If true, then it adds extra padding to make it equivalent to a C struct.
copy
: It creates another copy of the dtype object.
7. Numpy Array Creation Tutorial
There are various ways to create arrays in NumPy.
Arrays in Numpy can be created in multiple ways, with various number of Ranks, defining the size of the Array. Arrays can also be created with the use of various data types such as lists, tuples, etc.
Often, the elements of an array are originally unknown, but its size is known. Hence, NumPy offers several functions to create arrays with initial placeholder content. These minimize the necessity of growing arrays which is an expensive operation. For example np.zeros(), np.ones(), and np.empty() etc.
To create sequences of numbers, NumPy provides the arange
() function which is analogous to the Python built-in range
but returns an array.
arange
: returns evenly spaced values within a given interval. step size is specified.
7.1 Create NumPy Array From List
# Creation of Arrays
arr = np.array([10, 20, 30])
print("Array:",arr)
# Output:
# Array: [10 20 30]
7.2 Creating an Array From a List with Type Float
# Creating array from list with type float
arr = np.array([[10, 20, 40], [30,40,50]], dtype = 'float')
print ("Array created by using list: \n", arr)
# Output:
# Array created by using list:
# [[10. 20. 40.]
# [30. 40. 50.]]
7.3 Create a Sequence of Integers using arange()
# Create a sequence of integers
# from 0 to 20 with steps of 3
arr= np.arange(0, 20, 3)
print ("A sequential array with steps of 3:\n", arr)
# Output:
# A sequential array with steps of 3:
# [ 0 3 6 9 12 15 18]
8. Array Indexing in NumPy Tutorial
NumPy array indexing is used to access values in the 1-dimensional and, multi-dimensional arrays. Indexing is an operation, use this feature to get a selected set of values from a NumPy array. Note that the index in ndarray starts from zero hence, there is a difference between the value and where the value is located in an array. ndarray
can be indexed using the standard Python x[obj]
syntax, where x is the array and obj the selection. There are different kinds of indexing available depending on obj. Most of the following examples show the use of indexing when referencing data in an array. In this NumPy tutorial, you will learn various types of array indexing.
8.1 Single Element Indexing
Single element indexing works exactly like that for other standard Python sequences. It is 0-based and accepts negative indices for indexing from the end of the array.
# Access single element using index
arr = np.arange(11)
print(arr)
#[ 0 1 2 3 4 5 6 7 8 9 10]
print(arr[2])
#2
print(arr[-2])
#8
8.2 Multi-Dimenstional Array Indexing
# Access multi-dimensional array element
# using array indexing
arr =np.array([[10,20,30,40,50],[20,30,50,10,30]])
print(arr)
#[[10 20 30 40 50]
# [20 30 50 10 30]]
print(arr.shape)
#(2,5) # now x is 2-dimensional
print(arr[1,1])
#30
print(arr[0,4])
#50
print(arr[1,-1])
#30
8.3 Slicing
Python has basic slicing of arrays, and Numpy slicing extends slicing to N dimensions. Basic slicing occurs when obj is a slice
object (constructed by start:stop:step
notation inside of brackets), an integer, or a tuple of slice objects and integers.
# Access array elements using slicing
arr = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
x= arr[1:8:2]
print(x)
# Output: [1 3 5 7]
# Example
x=arr[-2:3:-1]
print(x)
# Output: [8 7 6 5 4]
# Example
x=arr[-2,10]
print(x)
[8 9]
Using slicing array indexing I will slice [:3, ::2]
these elements which means three rows for every two alternative columns.
# indexing in numpy
arr = np.array([[10, 20, 10, 40],
[40, 50, 70, 90],
[60, 10, 70, 80],
[30, 90, 40, 30]])
# Slicing array
x= arr[:3, ::2]
print (x)
# Output :
# [[10 10]
# [40 70]
# [60 70]]
8.4 Integer Array Indexing
Integer array indexing allows the selection of arbitrary items in the array based on their N-dimensional index. Each integer array represents a number of indices into that dimension. In this method, lists are passed for indexing for each dimension. One to one mapping of corresponding elements is done to construct a new arbitrary array.
In the following example, one element of the specified column from each row of the ndarray object is selected. Hence, the row index contains all row numbers, and the column index specifies the element to be selected.
# Integer array indexing
arr = np.arange(35).reshape(5, 7)
print(arr)
# [[ 0 1 2 3 4 5 6]
# [ 7 8 9 10 11 12 13]
# [14 15 16 17 18 19 20]
# [21 22 23 24 25 26 27]
# [28 29 30 31 32 33 34]]
# Array Index
x=arr[np.array([0, 2, 4]), np.array([0, 1, 2])]
print(x)
# [ 0 15 30]
8.5 Boolean Array Indexing
This advanced indexing occurs when an object is an array object of Boolean types, such as may be returned from comparison operators. Use this method when we want to pick elements from the array which satisfy some conditions.
For multi-dimensional NumPy arrays, you can access the elements as below
multi_arr [1, 2]
– To access the value at row 1 and column 2.multi_arr [1,:]
– To get the value at row 1 and all columns.multi_arr [:, 1]
– Access the value at all rows and columns 1.
# Boolean array indexing
arr = np.arange(12).reshape(3,4)
print(arr)
#[[ 0 1 2 3]
# [ 4 5 6 7]
# [ 8 9 10 11]]
rows = np.array([False,True,True])
wanted_rows= arr[rows, : ]
print(wanted_rows)
# [[ 4 5 6 7]
# [ 8 9 10 11]]
9. Convert NumPy Array to Python List
We can convert the Numpy array to the list by using tolist()
method, We may have a list of data elements that have been converted from the array using this method.
# Syntax of tolist()
ndarray.tolist()
Parameters: none
Returns: The possibly nested list of array elements.
Before going to convert from NumPy array
to Python list
we have to import the required module, after that, we have to create an array and then use the tolist()
method to convert array to list. After using this method we have to check the type of class using the type()
method.
9.1 Convert One Dimensional Array To List
# create array
array = np.array([10, 20, 30, 40])
print("Array:", array)
print(type(array))
#Array: [10 20 30 40]
# Convert list
list = array.tolist()
print("list:", list)
print(type(list))
#list: [10, 20, 30, 40]
9.2 Convert Multi Dimensional Array to list
# create array
array = np.array([[10, 20, 30, 40],
[50, 60, 70, 80],
[60, 40 ,20 ,10]])
print("Array:", array)
#Array: [[10 20 30 40]
# [50 60 70 80]
# [60 40 20 10]]
# Convert list
list = array.tolist()
print("list:", list)
#list: [[10, 20, 30, 40], [50, 60, 70, 80], [60, 40, 20, 10]]
10. Convert Python List to A NumPy Array
Lists can convert to arrays using the built-in functions in the Python NumPy library.
How to convert a list to an array in Python
NumPy
provides us with two functions to use when converting a list into an array:
- numpy.array()
- numpy.asarray()
numpy.array()
: Using numpy.array() This function of the numpy library allows a list as an argument and returns an array that contains all the elements of the list. See the example below: import numpy as np. …
# Create list
list = [20,40,60,80]
# Convert array
array = np.array(list)
print ("Array:", array)
# Output: Array: [20 40 60 80]
numpy.asarray()
: Using numpy.asarray() This function calls the numpy.array() function inside itself.
def asarray(a, dtype=None, order=None):
return array(a, dtype, copy=False, order=order)
The main difference between np.array()
and np.asarray()
is that the copy
flag is false
in the case of np.asarray()
, and true
(by default) in the case of np.array()
.
This means that np.array()
will make a copy of the object (by default) and convert that to an array, while np.asarray()
will not.
# Use asarray()
list = [20,40,60,80]
array = np.asarray(list)
print(" Array:", array)
# Output : Array: [20 40 60 80]
11. Numpy Array Properties in Tutorial
ndarray.shape
ndarray.ndim
ndarray.itemsize
ndaray.size
ndarray.dtype
11.1 ndarray.shape
To get the shape of a Python NumPy array use numpy.ndarray.shape
property. The array shape can be defined as the number of elements in each dimension and dimension is defined as a number of indices or subscripts, that can specify an individual element of an array.shape
attribute returns a tuple consisting of array dimensions. It can also use to resize the array. For example,
#Shape
array = np.array([[1,2,3],[4,5,6]])
print(array.shape)
# Output :
#(2, 3)
# Resize the array
array = np.array([[10,20,30],[40,50,60]])
array.shape=(3,2)
print(array)
# Output:
#[[10 20]
# [30 40]
# [50 60]]
NumPy also provides a numpy.reshape() function to resize an array. For example,
#reshape usage
array = np.array([[10,20,30],[40,50,60]])
new_array = array.reshape(3,2)
print(new_array)
# Output :
#[[10 20]
# [30 40]
# [50 60]]
11.2 ndarray.ndim
The ndim
property is used to find the dimensions of the array. For example,
# Usage of ndim
array = np.array([[1, 2, 3, 4],
[7, 8, 6, 7],
[9, 10, 11, 12]])
print(array.ndim)
#Outputs :
#2
11.3 ndarray.itemsize
The itemsize
property is used to get the size of each array item. It returns the number of bytes taken by each array element. For example,
# Finding the size of each item in the array
array = np.array([10,20,30])
print("Each item contain in bytes :",array.itemsize)
#Outputs:
#Each item contain in bytes: 4
11.4 ndarray.dtype
Use dtype function to check the data type of each array item. Consider the following example to check the data type of the array items. For example,
# Finding the data type of each array item
array = np.array([10,20,30])
print("Each item is of the type", array.dtype)
#Output:
#Each item is of the type int32
11.5 ndaray.size
To get the shape and size of the array, the size and shape function associated with the numpy array is used. For Example,
# Get shape and size of array
array = np.array([[10,20,30,40],[60,70,80,90]])
print("Array Size:", array.size)
print("Shape:", array.shape)
# Output:
#Array Size: 8
#Shape: (2, 4)
12. Operations Using in NumPy Tutorial
NumPy’s operations are divided into three main categories:
- Fourier Transform and Shape Manipulation
- Mathematical and Logical Operations
- Linear Algebra and Random Number Generation.
12.1 Arithmetic Operations
Arithmetic operators on arrays apply elementwise. A new array is created and filled with the result.
# Apply arithmetic operations on numpy arrays
arr1 = np.arange(16).reshape(4,4)
arr2 = np.array([1, 3, 2, 4])
# add()
add_arr = np.add(arr1,arr2)
print("Adding two arrays:\n",add_arr)
#Adding two arrays:
# [[ 1 4 4 7]
# [ 5 8 8 11]
# [ 9 12 12 15]
# [13 16 16 19]]
# substract()
sub_arr=np.subtract(arr1,arr2)
print("Subtracting two arrays:\n",sub_arr)
#Subtracting two arrays:
# [[-1 -2 0 -1]
# [ 3 2 4 3]
# [ 7 6 8 7]
# [11 10 12 11]]
# multiply()
mul_arr = np.multiply(arr1, arr2)
print("Multiplying the two arrays:\n",mul_arr)
#Multiplying the two arrays:
# [[ 0 3 4 12]
# [ 4 15 12 28]
# [ 8 27 20 44]
# [12 39 28 60]]
# divide()
div_arr = np.divide(arr1, arr2)
print("Dividing the two arrays:\n",div_arr)
#Dividing the two arrays:
# [[ 0. 0.33333333 1. 0.75 ]
# [ 4. 1.66666667 3. 1.75 ]
# [ 8. 3. 5. 2.75 ]
# [12. 4.33333333 7. 3.75 ]]
12.2 numpy.reciprocol()
This function returns the reciprocal of argument, element-wise. For elements with absolute values larger than 1, the result is always 0 because of the way in which Python handles integer division. For integer 0, an overflow warning is issued.
# To perform Reciprocal operation
arr1 = np.array([50, 10.3, 5, 1, 200])
rep_arr1=np.reciprocal(arr1)
print("After applying reciprocal function:\n",rep_arr1)
#After applying reciprocal function:
# [0.02 0.09708738 0.2 1. 0.005 ]
# Anotehr Example
arr2 = np.array([20], dtype = int)
rep_arr2=np.reciprocal(arr2)
print("After applying reciprocal function:\n",rep_arr2)
#After applying reciprocal function:
# [0]
12.3 numpy.power()
This NumPy power() 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.
# To perform power operation
arr1 = np.array([3, 10, 5])
pow_arr1 = np.power(arr1, 3)
print("Applying power function:\n",pow_arr1)
#Applying power function:
# [ 27 1000 125]
arr2 = np.array([3, 2, 1])
print("My second array:\n",arr2)
pow_arr2=np.power(arr1, arr2)
print("Applying power function again:\n",pow_arr2)
#Applying power function again:
# [ 27 100 5]
12.4 numpy.mod()
This function returns the remainder of the division of the corresponding elements in the input array. The function numpy.remainder()
also produces the same result.
# To perform mod function
# on NumPy array
import numpy as np
arr1 = np.array([7, 20, 13])
arr2 = np.array([3, 5, 2])
# mod()
mod_arr = np.mod(arr1, arr2)
print("Applying mod() function:",mod_arr)
# Applying mod() function: [1 0 1]
# remainder()
mod_arr = np.remainder(arr1, arr2)
print("Applying remainder() function:",mod_arr)
Applying remainder() function: [1 0 1]
Conclusion
In this Python NumPy Tutorial, you have learned what is NumPy? its features, advantages, and how to use NumPy arrays with sample python examples.
Happy Learning !!