NumPy - Numerical Python
NumPy (stands for Numerical Python ) is a fast and versatile library for the Python programming language, adding support for large, N-dimensional arrays and matrices, along with a large collection of comprehensive mathematical functions to operate on these multidimensional arrays . NumPy was created in 2005 by Travis Oliphant. It is one of the fundamental package for scientific computing in Python. NumPy arrays are stored at one continuous place in memory unlike Python lists (which can grow dynamically ), so processes can access and manipulate them very fast and efficiently.
How To Install NumPy
Prerequisites
- Python installed on your system
pip3 install numpy
Importing the NumPy module
>>> import numpy
If you have large amounts of calls to NumPy functions , it can become tedious to write numpy.x() over and over again. Instead, it is common to import under the briefer name np.
>>> import numpy as np
Create a NumPy array
Creating a 1-D NumPy array with continuous 9 values.
>>> import numpy as np
>>> npArr = np.array([1, 2, 3, 4, 5,6,7,8,9])
>>> print(npArr)
[1 2 3 4 5 6 7 8 9]
Check the type of NumPy array
>>> print(type(npArr))
<class 'numpy.ndarray'>
Create a 2-D NumPy array
Creating a 2-D NumPy array with 2 rows and 4 columns.
Create a 3-D NumPy array
Creating a 3-D NumPy array with 2 rows, 3 columns and 4 depth.
>>> npArr = np.array([[[1, 2, 3,4], [5, 6, 7,8],[9, 10, 11,12]], [[1, 2, 3,4], [5, 6, 7,8],[9, 10, 11,12]]])
>>> print(npArr)
[[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]]
NumPy Array Shape
The shape property of a NumPy array returns a tuple with the size of each array dimension.1-D NumPy Array shape
>>> import numpy as np
>>> npArr = np.array([1, 2, 3, 4, 5,6,7,8,9])
>>> npArr.shape
(9,)
Here npArr is a 1-D NumPy array so the shape of the array is (9,), this means that the array has continuous 9 values only.
2-D NumPy Array shape
>>> npArr = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
>>> npArr.shape
(2, 4)
Here npArr is a 2-D NumPy array so the shape of the array is (2, 4), this means that the array has 2 rows and 4 columns dimensions.
3-D NumPy Array shape
>>> import numpy as np
>>> npArr = np.array([[[1, 2, 3, 4], [5, 6, 7,8],[9, 10, 11,12]], [[1, 2, 3,4], [5, 6, 7,8],[9, 10, 11,12]]])
>>> npArr.shape
(2, 3, 4)
Here npArr is a 3-D NumPy array so the shape of the array is (2, 3, 4), this means that the array has 2 rows, 3 columns and 4 depth dimensions.
Related Topics