Python Weekly: NumPy Basics (NumPy Arrays)- Part 1
NumPy is a powerful linear algebra library for Python.NumPy is also incredibly fast, as it has bindings to C libraries. It is the core library for scientific computing in Python. It provides a high-performance multidimensional array object and tools for working with these arrays.
Installation
pip3 install numpy (using pip3)
or
conda install numpy (using anaconda environment)
Using Numpy
Once installed, we can import the NumPy dependency as
import numpy as np
NumPy Arrays
NumPy arrays come in 2 flavors. Vectors and matrices. Vectors are strictly 1-dimensional arrays and matrices are n-dimensional arrays.
Creating NumPy Arrays
From Python list
test_list = [1,2,3,4]
np.array(test_list)
output : array([1,2,3,4])
test_matrix = [[1,2,3,4],[5,6,7,8,9],[10,11,12,13]]
np.array(test_matrix)
output : array([[1,2,3,4],[5,6,7,8,9],[10,11,12,13]])
Built-In Methods
NumPy provides a lot of built-in methods to generate arrays.
arange
It generates evenly spaced values within a given interval.
np.arange(0,10)
output : array([0,1,2,3,4,5,6,7,8,9])
np.arange(0,11,2) # evenly spaced integer
output : array([0,2,4,6,8,10])
Zeros and Ones
It generates an array of given shape filled with zeros
np.zeros(4)
output : array([0.,0.,0.,0.])
np.zeros((4,4))
output : array([[0.,0.,0.,0.],
[0.,0.,0.,0.],
[0.,0.,0.,0.],
[0.,0.,0.,0.]])
np.ones(4)
output : array([1.,1.,1.,1.])
np.ones((4,4))
output : array([[1.,1.,1.,1.],
[1.,1.,1.,1.],
[1.,1.,1.,1.],
[1.,1.,1.,1.]])
linspace
It generates an array with an evenly spaced interval.
np.linspace(0,10,3) # np.linspace(start,end,interval)
output : array([ 0., 5., 10.])
np.linspace(0,5,21)
output : array([0. , 0.25, 0.5 , 0.75, 1. , 1.25, 1.5 , 1.75, 2. , 2.25, 2.5 ,
2.75, 3. , 3.25, 3.5 , 3.75, 4. , 4.25, 4.5 , 4.75, 5. ])
eye
It generates an identity matrix.
np.eye(3)
output : array([
[1.,0.,0.],
[0.,1.,0.],
[0.,0.,1.]
])
There are more ways to generate random number arrays. And there are some array attributes and methods that will prove useful in day to day life working with NumPy arrays.
Stay tuned for the next part ………
Thank you for taking the time and reading the article. Hope you will appreciate it.