Basic and tricky numpy functions

Main preprocessing techniques for Numpy package

In [ ]:
import numpy as np
  1. read array from text
  2. save as npy
  3. read from npy
In [ ]:
text_path = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'

stack an array to matrix vertically and horizontally using hstack and vstack functions

In [ ]:
a = np.random.randint(0,100,size=(3,3))
b = np.random.randint(0,100,size=(1,3))
# horizontal stacking
# vertical stacking

replace items that satisfy a condition with another value

In [ ]:
a = np.random.randint(0,100,size=(10,10))
# items bigger than 20 -> -1

get the intersection between two python numpy arrays

In [ ]:
a = np.arange(10)
b = np.arange(5) * 2

remove items of an array from another array

In [ ]:
a = np.arange(10)
b = np.arange(5) * 2

extract all elements between a given range

In [ ]:
a = np.arange(10)
# items between 5 and 10

change columns order in a 2d numpy array

In [ ]:
a = np.arange(12).reshape((3,4))
#new_order of columns 3 , 0 , 1 , 2
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]
[[ 3  0  1  2]
 [ 7  4  5  6]
 [11  8  9 10]]

count elements

In [ ]:
a = np.random.randint(0,100,size=(100,100)) 
#count of each element

sort by column

In [ ]:
a = np.random.randint(0,100,size=(10,10))
# sort based on column 3

generate one hot encoding

In [ ]:
a = np.random.randint(0,100,size=(10,10))
# one hot of array

numpy broadcasting . we have two arrays with shape [a] and [b]. we want to compute distance between each two elements using broadcasting

In [ ]:
a = np.random.randint(0,10,size=(7))
b = np.random.randint(0,10,size=(5))
# your code here

arithmetic operation

In [ ]:
a = np.random.randint(0,100,size=(10,10))
b = np.random.randint(1,100,size=(10,10))
# elementwise sum , subtract , multiply and devide

max values of columns

In [ ]:
a = np.random.randint(0,100,size=(10,10))
#max of each column in an array

check array similarity using allclose function

In [ ]:
a = np.random.randint(0,100,size=(10,10))
b = a + np.random.rand(10,10) * 1e-6
# if two matrix have closer values than a threshold return true

matrix multiplication

In [ ]:
a = np.random.randint(0,100,size=(6,8))
b = np.random.randint(0,100,size=(8,10))
# return A x B and it's shape

compute rank of matrix using numpy.linalg

In [ ]:
a = np.random.randint(0,100,size=(6,8))

compute matrix norm using numpy.linalg

In [ ]:
a = np.random.randint(0,100,size=(6,8))

compute matrix inverse using numpy.linalg

In [ ]:
a = np.random.randint(0,100,size=(8,8))