# Numpy Small Cheatsheet

May 1, 2018 - 5 minute read - Category:

## 1. Constructing Arrays in NumPy

np.array([1,2,3,4]) # From list

np.eye(4) # Identity matrix with 4 rows and 4 cols

np.zeros((3,4)) # Zero matrix with 3 rows and 4 cols

np.ones((3,4))  # One matrix with 3 rows and 4 cols

np.full((3,2), 5) # Same as 5*np.ones((3,2))

np.diag([1,2,3,4]) # Diagonal matrix

np.arrange(start, stop, step) # Almost same as bulit-in range

np.linspace(start, end, number, endpoint=False) #Linear spaced vector


## 2. Constructing Random Arrays

np.random.random((3,3)) # Uniform random number with shape (3,3)

np.random.randint(lower, up, (3,2))

np.random.normal(miu, sigma, shape)


## 3. Manipulating Arrays

X.reshape((a,b)) # a or b can equal to -1 for auto conversion

X.mean(); X.std(); X.max(); X.min(); X.sum() # Statistical Res

X.sum(axis=0) # Add vals in each cols, Retain col number
X.sum(axis=1) # Add vals in each rows, Retain row number

np.delete(X, 2, axis=0) # Delete row 0
np.delete(X, [0,1], axis=1) # Delete col 0 and col 1

np.append(X, [[10, 11, 12]], axis=0) # Add new row
np.insert(X, col_num, 5, axis=1) # Instert a new col

np.diag(X, k=0) # Find diagnoal values

np.unique(X) # Find unique valuse in X

np.sort(X) # Output a sorted view of X
X.sort() # Change X
X.sort(axis=0) # Sort by rows

np.hstack(X,Y); np.vstack(X,Y) # Stack Arrays

x = np.array([1,2,3,4,5])
y = np.array([6,7,2,8,4])
np.intersect1d((x,y)) #[2,4]
np.setdiff1d((x,y)) #[1,3,5]
np.union1d((x,y)) #[1,2,3,4,5,6,7,8]


## 4. Slicing Arrays

# Differentiate view and copy of slices
M = X[:,:]
N = X[:,:].copy()

# Boolean Indexing
X[(X>10) & (X<17)] = -1


np.ones((1,4)) + np.ones((3,1)) # 3*4, all 2
np.ones((4,4)) + 1 # 4*4, all 2
np.eye(4) + np.array([1,2,3,4]) # Add row by row
np.eye(4) + np.array([,,,]) # Add col by col


Feasible

A (2d Array): 4 x 3
x (1d Array):     3


Feasible

A (2d Array): 4 x 3
x (1d Array): 4 x 1


NOT Feasible

A (2d Array): 4 x 3
x (1d Array):     4


## 6. Dark Magic

### 6.1 Add an extra dimension to a array

a = np.array([1,2,3])
a[None, ]


Remineded by Sam, I learned that there is a dedicated NumPy variable called newaxis that can improve the readability:

np.newaxis is None # True
a[None, ]


### 6.2 How to ‘transpose’ a vector

a = np.array([1,2,3])
print(a[:,None])


### 6.3 Difference in the order of computing when multiplying a matrix and vector

x = np.array([[1,2],[3,4])
v = np.array([9,10])

print(np.dot(x,v))
# Equivalent to
[[ 1 2 ]  * [[9 ]
[ 3 4 ]]    ]
print(np.dot(v,x))
# Equivalent to
[9 10] * [[ 1 2 ]
[ 3 4 ]]