Home »
Python
Python NumPy Tutorial
In this tutorial, you will learn about the Python's NumPy library, its installation, creating programs using NumPy, and NumPy's methods.
By Sapna Deraje Radhakrishna Last updated : April 12, 2023
Table of Contents
What is NumPy in Python?
NumPy is a library for the Python programming language which is specially designed for implementing large, multi-dimensional arrays and matrices. It also provides a large collection of built-in method to work on the arrays and matrices. In other words, we can say that NumPy is an array processing package which provides high-performance multidimensional array object and utilities to work with arrays.
NumPy is a basic package for scientific computation with python. It is a linear algebra library and is very important for data science with Python since almost all of the libraries in the pyData ecosystem rely on NumPy as one of their main building blocks. It is incredibly fast, as it has bindings to C language.
What are the features of Python NumPy?
Some of the many features, provided by numpy are as always,
- N-dimensional array object
- Broadcasting functions
- Utilities for integrating with C / C++
- Useful linear algebra and random number capabilities
How to Install NumPy Library?
There are two ways to install NumPy library: Using pip and using anaconda.
1) Using pip
pip install numpy
Installing output
pip install numpy
Collecting numpy
Downloading https://files.pythonhosted.org/packages/60/9a/a6b3168f2194fb468dcc4cf54c8344d1f514935006c3347ede198e968cb0/numpy-1.17.4-cp37-cp37m-macosx_10_9_x86_64.whl (15.1MB)
100% |████████████████████████████████| 15.1MB 1.3MB/s
Installing collected packages: numpy
Successfully installed numpy-1.17.4
2) Using Anaconda
conda install numpy
Importing NumPy Library
For using NumPy library functionalities, we need to import numpy package. It enables all the functionalities to be used in the Python program. The import statement to use NumPy library is:
import numpy as np
Arrays in NumPy
Numpy's main object is the homogeneous multidimensional array. Numpy arrays are two types: vectors and matrices. vectors are strictly 1-d arrays and matrices are 2-d.
In Numpy dimensions are known as axes. The number of axes is rank. The below examples lists the most important attributes of a ndarray object.
NumPy Example 1: Print the most important attributes of a ndarray object
# importing package
import numpy as np
# creating array
arr = np.array([[11,12,13],[14,15,16]])
print("Array is of type {}".format(type(arr)))
print("No. of dimensions {}".format(arr.ndim))
print("shape of array:{}".format(arr.shape))
print("size of array:{}".format(arr.size))
print("type of elements in the array:{}".format(arr.dtype))
Output
Array is of type <class 'numpy.ndarray'>
No. of dimensions 2
shape of array:(2, 3)
size of array:6
type of elements in the array:int64
Creating a NumPy Array
Creating a numpy array is possible in multiple ways. For instance, a list or a tuple can be cast to a numpy array using the. array() method (as explained in the above example). The array transforms a sequence of the sequence into 2-d arrays, sequences of sequences into a 3-d array and so on.
To create sequences of numbers, NumPy provides a function called arange that returns arrays instead of lists.
Syntax to create a NumPy array is:
# returns evenly spaced values
# within a given interval.
arange([start,] stop [,step], dtype=None)
NumPy Example 2: Create an array of integers
# Import NumPy package
import numpy as np
# Creating array of integers
numbers = np.array([10, 20, 30])
# Printing array elements
print(numbers)
# Pritning the type of array
print(type(numbers))
Output
# Import NumPy package
import numpy as np
# Creating array of integers
numbers = np.array([10, 20, 30])
# Printing array elements
print(numbers)
# Pritning the type of array
print(type(numbers))
NumPy Example 3: Remove elements from an array
In this example, we will remove specific elements from a given NumPy array. We will create an array of integers and will remove the elements which will be divisible by 5.
# Import numpy
import numpy as np
# Creating a numpy array
arr = np.array([i for i in range(50)])
# Display original array
print("Original array:\n",arr,"\n")
# Defining some elements
multiples = [i for i in range(50) if i%50==0]
# Deleting these elements
res = np.delete(arr,multiples)
# Display result
print("Result:\n",res)
Output
Original array:
[ 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 35 36 37 38 39 40 41 42 43 44 45 46 47
48 49]
Result:
[ 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 35 36 37 38 39 40 41 42 43 44 45 46 47 48
49]
NumPy Example 4: Use zeros(), ones(), and empty() functions with array
The function zeros() - creates an array full of zeros, the function ones() - creates an array full of ones, and the function empty() - creates an array whose initial content is random and depends on the state of the memory. By default, the dtype of the created array is float64.
# importing package
import numpy as np
x = np.zeros((3,4))
print("np.zeros((3,4))...")
print(x)
x = np.ones((3,4))
print("np.ones((3,4))...")
print(x)
x = np.empty((3,4))
print("np.empty((3,4))...")
print(x)
x = np.empty((1,4))
print("np.empty((1,4))...")
print(x)
Output
np.zeros((3,4))...
[[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]]
np.ones((3,4))...
[[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]]
np.empty((3,4))...
[[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]]
np.empty((1,4))...
[[1.63892563e-316 0.00000000e+000 2.11026305e-312 2.56761491e-312]]
Creating NumPy 2D Arrays (Matrices)
Consider the below example to create NumPy 2D array,
# importing module
import numpy as np
# 2-D array
arr_2d = np.array([[10,15,20],[25,30,35],[40,45,50]])
# printing array
print(arr_2d)
"""
Output:
[[10 15 20]
[25 30 35]
[40 45 50]]
"""
Python NumPy Functions
Some more function available with NumPy to create an array are,
1) linspace() function
It returns an evenly spaced numbers over a specified interval.
Syntax
linspace(start, stop, num=50, endpoint=True, restep=False, dtype=None)
Example
# importing package
import numpy as np
x = np.linspace(1,3,num=10)
print(x)
Output
[1. 1.22222222 1.44444444 1.66666667 1.88888889 2.11111111
2.33333333 2.55555556 2.77777778 3. ]
2) eye() function
It returns a 2-D array with ones on the diagonal and zeros elsewhere.
Syntax
eye(N, M=None, k=0, dtype=<class 'float'>, order='C')
Example
# importing package
import numpy as np
x = np.eye(4)
print(x)
Output
[[1. 0. 0. 0.] [0. 1. 0. 0.]
[0. 0. 1. 0.]
[0. 0. 0. 1.]]
3) random() function
It creates an array with random numbers
Example
# importing package
import numpy as np
x = np.random.rand(5)
print("np.random.rand(5)...")
print(x)
x = np.random.rand(5,1)
print("np.random.rand(5,1)...")
print(x)
x = np.random.rand(5,1,3)
print("np.random.rand(5,1,3)...")
print(x)
# returns a random number
x = np.random.randn()
print("np.random.randn()...")
print(x)
# returns a 2-D array with random numbers
x = np.random.randn(2,3)
print("np.random.randn(2,3)...")
print(x)
x = np.random.randint(3)
print("np.random.randint(3)...")
print(x)
# returns a random number in between low and high
x = np.random.randint(3,100)
print("np.random.randint(3,100)...")
print(x)
# returns an array of random numbers of length 34
x = np.random.randint(3,100,34)
print("np.random.randint(3,100,34)...")
print(x)
Output
np.random.rand(5)...[0.87417146 0.77399086 0.40012698 0.37192848 0.98260636]
np.random.rand(5,1)...
[[0.712829 ]
[0.65959462]
[0.41553044]
[0.30583293]
[0.83997539]]
np.random.rand(5,1,3)...
[[[0.75920149 0.54824968 0.0547891 ]]
[[0.70911911 0.16475541 0.5350475 ]]
[[0.74052103 0.4782701 0.2682752 ]]
[[0.76906319 0.02881364 0.83366651]]
[[0.79607073 0.91568043 0.7238144 ]]]
np.random.randn()...
-0.6793254693909823
np.random.randn(2,3)...
[[ 0.66683143 0.44936287 -0.41531392]
[ 1.86320357 0.76638331 -1.92146833]]
np.random.randint(3)...
1
np.random.randint(3,100)...
53
np.random.randint(3,100,34)...
[43 92 76 39 78 83 89 87 96 59 32 74 31 77 56 53 18 45 78 21 46 10 25 86
64 29 49 4 18 19 90 17 62 29]
4) Reshape function (shape manipulation)
An array has a shape given by the number of elements along each axis,
Example
# importing package
import numpy as np
x = np.floor(10*np.random.random((3,4)))
print(x)
print(x.shape)
Output
[[0. 2. 9. 4.]
[0. 4. 1. 7.]
[9. 7. 6. 2.]]
(3, 4)
The shape of an array can be changes with various commands. However, the shape commands return all modified arrays but do not change the original array.
# importing package
import numpy as np
x = np.floor(10*np.random.random((3,4)))
print(x)
# returns the array, flattened
print("x.ravel()...")
print(x.ravel())
# returns the array with modified shape
print("x.reshape(6,2)...")
print(x.reshape(6,2))
# returns the array , transposed
print("x.T...")
print(x.T)
print("x.T.shape...")
print(x.T.shape)
print("x.shape...")
print(x.shape)
Output
[[3. 1. 0. 6.] [3. 1. 2. 4.]
[7. 0. 0. 1.]]
x.ravel()...
[3. 1. 0. 6. 3. 1. 2. 4. 7. 0. 0. 1.]
x.reshape(6,2)...
[[3. 1.]
[0. 6.]
[3. 1.]
[2. 4.]
[7. 0.]
[0. 1.]]
x.T...
[[3. 3. 7.] [1. 1. 0.]
[0. 2. 0.]
[6. 4. 1.]]
x.T.shape...
(4, 3)
x.shape...
(3, 4)
Example with additional methods
# importing package
import numpy as np
x = np.floor(10*np.random.random((3,4)))
print(x)
#Return the maximum value in an array
print("x.max():", x.max())
# Return the minimum value in a array
print("x.min():", x.min())
# Return the index of max value in an array
print("x.argmax():", x.argmax())
# Return the index of min value in an array
print("x.argmin():", x.argmin())
Output
[[4. 0. 5. 2.] [8. 5. 9. 7.]
[9. 3. 5. 5.]]
x.max(): 9.0
x.min(): 0.0
x.argmax(): 6
x.argmin(): 1
More on Python NumPy