NumPy, which stands for Numerical Python, is the fundamental package for scientific computing with Python. It is a Python library with impressive capabilities that provides high-performance multidimensional array objects and tools for working with arrays. It is mainly used in machine learning, data science, signal processing, linear algebra operations, and scientific and engineering computing.
Installing NumPy
It can be installed with pip, and conda, with a package manager on Linux and macOS, or from source. For detailed instruction please see numpy official installation guide.
# using pip
pip install numpy
# using conda
conda install numpy
Now, Let’s discuss some functions of the NumPy library. First, we have to import it.
import numpy as np
Creating Arrays
# python array
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(a)
# numpy array
b = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
print(b)
# numpy array from tuple
c = np.array((1, 2, 3, 4, 5, 6, 7, 8, 9, 10))
print(c)
Output
# 0-D
a = np.array(36)
print(a.ndim)
# 1-D
b = np.array([1, 2, 3])
print(b.ndim)
# 2-D
c = np.array([[1, 2, 3], [4, 5, 6]])
print(c.ndim)
# 3-D
d = np.array([
[[1, 2, 3], [4, 5, 6]],
[[1, 2, 3], [4, 5, 6]]
])
print(d.ndim)
Output
0
1
2
3
Basic Operations
a = np.array([1, 2, 3, 4, 5])
print(a)
a = a * 2
print(a)
b = np.array([2, 3, 4, 5, 6])
print(b)
c = a - b
print(c)
d = b > 4
print(d)
Output
[1 2 3 4 5]
[2 4 6 8 10]
[2 3 4 5 6]
[0 1 2 3 4]
[False False False True True]
Data Type Hierarchy
You can check that an array contains integers, floating-point numbers, strings, or Python objects using data superclasses like np.integer, np.floating with the np.issubdtype function.
i = np.ones(5, dtype=np.uint16)
print(i)
f = np.ones(5, dtype=np.float32)
print(f)
isint = np.issubdtype(i.dtype, np.integer)
print(isint)
isfloat = np.issubdtype(f.dtype, np.floating)
print(isfloat)
Output
[1 1 1 1 1]
[1. 1. 1. 1. 1.]
True
True
Reshaping Arrays
You can convert an array shape using reshape function.
a = np.arange(12)
print(a)
b = a.reshape((3, 4))
print(b)
Output
[0 1 2 3 4 5 6 7 8 9 10 11]
[[0 1 2 3]
[4 5 6 7]
[8 9 10 11]]
Raveling Arrays
NumPy ravel function is used to flatten the given array.
a = np.array([[1, 2, 3], [4, 5, 6]])
print(a)
b = np.ravel(a)
print(b)
Output
[[1 2 3]
[4 5 6]]
[1 2 3 4 5 6]
Besides the above-mentioned, NumPy has many functions and uses.