Numpy tutorial for Array and Matrix Part-I

Numpy is the main library for numerical and scientific computing in Python. Numpy basically stands for Numerical python. It is used to perform the numerical operation on arrays. It provides a rich set of methods and features for performing operations on arrays and matrices. Numpy is better than Python list in terms of size, functionality, and performances.

There are lots of data science and machine learning libraries like Scipy, Matplotlib, Scikit Learn, Tensorflow depends upon Numpy.

This course is basically covers basic of Numpy for the data science beginner. In this course you will learn about how to create numpy array, matrix and their basic operations.

#import numpy library
import numpy as np

Create a vector or array

row_vect=np.array([1,2,3,4,5,6])
print("Row_vector =",row_vect)
col_vect=np.array([[1],[2],[3],[4],[5],[6]])
print("Col_vector = ")
print(col_vect)

View Number of dimension

row_vect.ndim
col_vect.ndim

Select and Slice the elements from the array

#select 2nd element from row_vect
#since array indexing start from zero therefore second element would be
print(row_vect[1])

#same concept here also apply
print(col_vect[1])

#Slice element from 2nd to 5th in row_vect
print(row_vect[2:5])

#same concept here also apply
print(col_vect[2:5])

#Select all element from position 2
print(row_vect[2:])

Transpose of the matrix

m#Transpose of a matrix
new_row_vect=row_vect.T
print(new_row_vect)

new_col_vect=col_vect.T
print(new_col_vect)

Create a matrix

#Create a matrix
mat=np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]])
print(mat)
array([[ 1,  2,  3,  4],  
[ 5, 6, 7, 8],
[ 9, 10, 11, 12],
[13, 14, 15, 16]])

Shape of matrix

#view shape
mat.shape

View total elements in the matrix

#view total element
mat.size

Dimension of matrix

#view dimension of matrix
mat.ndim

Maximum/Minimum element in the matrix

#Maximum element in the Matrix
mat.max()
#Minimum element in the Matrix
mat.max()
#Maximum element by the column of the matrix
np.max(mat,axis=0)
#Maximum element by the row of the matrix
np.min(mat,axis=1)
#Minimum element by the column of the matrix
np.min(mat,axis=0)
#Minimum element by the row of the matrix
np.min(mat,axis=1)

Diagonal of the matrix

mat.diagonal()

Sum of diagonal of the matrix

mat.diagonal().sum()

Rank of the matrix

np.linalg.matrix_rank(mat)

Flatten the matrix

mat.flatten()

Calculate the determinant of the matrix

np.linalg.det(mat)

About Mitra N Mishra 35 Articles
Mitra N Mishra is working as a full-stack data scientist.

Be the first to comment

Leave a Reply