Python NumPy Tutorial – NumPy ndarray & NumPy Array
Master Python with 70+ Hands-on Projects and Get Job-ready - Learn Python
In our last Python Library tutorial, we studied Python SciPy. Now we are going to study Python NumPy.
In this NumPy tutorial, we are going to discuss the features, Installation and NumPy ndarray.
Moreover, we will cover the data types and array in NumPy. So, let’s begin the Python NumPy Tutorial.
What is NumPy?
A library for Python, NumPy lets you work with huge, multidimensional matrices and arrays.
Along with that, it provides a gamut of high-level functions to perform mathematical operations on these structures.
Here is a short brief about it:
- Author- Travis Oliphant
- First Release- 1995 (Released as Numeric; Changed to NumPy in 2006)
- Stable Release- June, 2018
- Written in- Python Programming, C
Python NumPy is cross-platform and BSD-licensed. We often use it with packages like Matplotlib and SciPy.
This can be seen as an alternative to MATLAB. The term ‘Numpy’ is a portmanteau of the words ‘NUMerical’ and ‘PYthon’.
Numpy Tutorial – Features of Numpy
In this Python NumPy Tutorial, we are going to study the feature of NumPy:
- NumPy stands on CPython, a non-optimizing bytecode interpreter.
- Multidimensional arrays.
- Functions and operators for these arrays.
- Python Alternative to MATLAB.
- ndarray- n-dimensional arrays.
- Fourier transforms and shapes manipulation.
- Linear algebra and random number generation.
Numpy Tutorial – How to Install NumPy?
You can use pip to install numpy-
pip install numpy
Then you can import it as-
>>> import numpy as np
Numpy Tutorial – NumPy ndarray
This is one of the most important features of numpy. ndarray is an n-dimensional array, a grid of values of the same kind.
A tuple of nonnegative integers indexes this tuple. An array’s rank is its number of dimensions.
Let’s take a few examples.
>>> a=np.array([1,2,3]) >>> type(a)
Output
<class ‘numpy.ndarray’>
>>> a.shape
Output
>>> a[0],a[2]
Output
>>> a[1]=5 >>> a
Output
As you can see, the array’s shape is (3,). What happens when we build an array of more than one dimension?
Let’s see.
>>> b=np.array([[2,7,9],[5,1,3]]) >>> b
Output
[5, 1, 3]])
>>> b[0,1]
Output
>>> b.shape
Output
>>> b.size
Output
1. How to Create NumPy Array?
The following lines of code create a few more arrays:
>>> np.arange(7) #This is like range in Python
Output
>>> np.random.random((3,3)) #Fills in random values
Output
[0.37222497, 0.13230271, 0.40858618],
[0.74455771, 0.52119999, 0.6927821 ]])
>>> np.ones((2,3))
Output
[1., 1., 1.]])
>>> np.zeros((1,2))
Output
>>> np.eye(3) #Identity matrix
Output
[0., 1., 0.],
[0., 0., 1.]])
>>> np.full((3,2),7) #Matrix of constants
Output
[7, 7],
[7, 7]])
>>> np.linspace(1,2,4) #4 values spaced evenly between, and including, 1 and 2.
Output
>>> np.empty([2,3]) #Empty array
Output
[0., 4., 0.]])
2. Some Parameters
>>> np.array([1,3,4],ndmin=3) #Minimum dimension
Output
>>> np.array([1,3,4],dtype=complex) #Data type
Output
Numpy Tutorial – Data Types
As we’ve said before, a NumPy array holds elements of the same kind.
If while creating a NumPy array, you do not specify the data type, NumPy will decide it for you.
We have the following data types-
bool_, int_, intc, intp, int8, int16, int32, int64, uint8, uint16, uint32, uint64, float_, float16, float32, float64, complex_, complex64, complex128
We can confirm:
>>> np.dtype(np.int32)
Output
>>> np.dtype('i4')
Output
>>> np.dtype('i8')
Output
Functions of NumPy Array
Let’s take a look at all that we can do to an array and what more we can find out about it.
>>> a=np.array([[1,2,3],[4,5,6]]) >>> a.reshape(3,2)
Output
[3, 4],
[5, 6]])
>>> a.ndim #Number of array dimensions
Output
>>> np.array([[1,2,3],[4,5,6]]).itemsize #Length of each element in bytes
Output
>>> np.array([[1,2,3],[4,5,6]],dtype=np.int8).itemsize
Output
>>> a
Output
[4, 5, 6]])
>>> a.flags
Output
F_CONTIGUOUS: False
OWNDATA: True
WRITEABLE: True
ALIGNED: True
WRITEBACKIFCOPY: False
UPDATEIFCOPY: False
Numpy Array Indexing
It is possible to slice you NumPy arrays- with multiple slices for multidimensional arrays.
>>> a=np.array([[1,2,3],[4,5,6],[7,8,9]]) >>> b=a[:2,1:3] >>> b
Output
[5, 6]])
>>> a[1,2]
Output
>>> b[0,0]=79 >>> a
Output
[ 4, 5, 6],
[ 7, 8, 9]])
As you can see, changes to a slice modify an original.
>>> a[1,:]
Output
>>> a[1:2,:]
Output
>>> a[:,1]
Output
1. Integer Indexing
It is possible to create an array from another.
>>> a=np.array([[1,2],[3,4],[5,6]]) >>> a[[0,1,2],[0,1,0]] #Prints elements at [0,0], [1,1], and [2,0]
Output
Let’s pick elements-
>>> a = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]]) >>> b = np.array([0, 2, 0, 1]) >>> b
Output
>>> a[np.arange(4), b]
Output
>>> a[np.arange(4), b]+=10 >>> a
Output
[ 4, 5, 16],
[17, 8, 9],
[10, 21, 12]])
2. Boolean Indexing
This will let you pick elements that satisfy a condition.
>>> a=np.array([[1,2],[3,4],[5,6]]) >>> boolean=(a>3) >>> boolean
Output
[False, True],
[ True, True]])
>>> a[boolean]
Output
Mathematical Functions on Arrays in NumPy
Let’s now look at some mathematical functions to call on arrays.
>>> a=np.array([[1,2,3],[4,5,6]]) >>> b=np.array([[7,8,9],[10,11,12]]) >>> np.add(a,b) #a+b does the same
Output
[14, 16, 18]])
>>> np.subtract(a,b) #Same as a-b
Output
[-6, -6, -6]])
>>> np.multiply(a,b) #a*b works too
Output
[40, 55, 72]])
>>> np.divide(a,b) #Same as a/b
Output
[0.4 , 0.45454545, 0.5 ]])
>>> np.sqrt(a) #Produces square root
Output
[2. , 2.23606798, 2.44948974]])
>>> a=np.array([[1,2],[3,4]]) >>> np.sum(a)
Output
>>> np.sum(a,axis=0) #Sum of each column
Output
>>> np.sum(a,axis=1) #Sum of each row
Output
To transpose this matrix:
>>> a.T
Output
[2, 4]])
>>> np.array([1,3,2]).T #NOP
Output
Some functions that operate on a larger context-
>>> x=np.array([[1,2],[3,4]]) >>> y=np.array([[5,6],[7,8]]) >>> v=np.array([9,10]) >>> w=np.array([11,12]) >>> v.dot(w) #Same as np.dot(v,w)
Output
>>> x.dot(v)
Output
>>> x.dot(y)
Output
[43, 50]])
So, this was all about Python NumPy Tutorial. Hope you like our explanation.
Python Interview Questions on NumPy
- What is Python NumPy array?
- What is the purpose of NumPy in Python?
- What is the difference between Pandas and NumPy in Python?
- How does NumPy work in Python?
- What functions does NumPy provide in Python?
Conclusion
Hence, in this Python NumPy Tutorial we studied, how to install NumPy, NumPy ndarray.
In addition, we discussed NumPy Array with its Functions and data types. This sums it up for NumPy.
Did you know we work 24x7 to provide you best tutorials
Please encourage us - write a review on Google
Thanku sir as compare to other tutorial your tutorial easily understand definately anyone student read
Hi Birajdar,
We feel motivated when our loyal reader appriciate the efforts, we made in our every Python tutorial. Hope, you are exploring other Python articles.
Do share with your peer groups.
Regards,
DataFlair
step no 8 , should it be a[0, 1] = 79 , in order to get [[ 1 79 3]
[ 4 5 6]
[ 7 8 9]] as an output ?
Hi Remya,
Thanks for the comment on Python Numpy Tutorial. Changing that value in b also changes it for a, since both points to the same object.
Hope, now you get it.
Regards,
DataFlair
i am getting this kind of error how to resolve this
import sklearn
Traceback (most recent call last):
File “”, line 1, in
File “C:\Users\kishan yadav\AppData\Local\Programs\Python\Python37\lib\site-packages\sklearn\__init__.py”, line 64, in
from .base import clone
File “C:\Users\kishan yadav\AppData\Local\Programs\Python\Python37\lib\site-packages\sklearn\base.py”, line 11, in
from scipy import sparse
File “C:\Users\kishan yadav\AppData\Local\Programs\Python\Python37\lib\site-packages\scipy\sparse\__init__.py”, line 231, in
from .csr import *
File “C:\Users\kishan yadav\AppData\Local\Programs\Python\Python37\lib\site-packages\scipy\sparse\csr.py”, line 15, in
from ._sparsetools import csr_tocsc, csr_tobsr, csr_count_blocks, \
ImportError: DLL load failed: The specified module could not be found.
>>> from .base import clone
Traceback (most recent call last):
File “”, line 1, in
ModuleNotFoundError: No module named ‘__main__.base’; ‘__main__’ is not a package
>>> pip install clone
To resolve this you can remove the dot(.) from the import statement.
Thank you for such a great reading material on numpy!