What is NumPy? - NumPy v1.23 Manual

import numpy as np

In-place, copy or view

Array Construction

a = np.array( [[1,3,4],[1,2,4]] ) #conversion=
b = np.empty_like(A) # empty array with same shape
c = np.zeros(a.shape)   # Create array with shape of other array
d = np.ones((3, 3, 3))
e = np.arange(10) #like build-in range
f = np.loadtxt("heart_disease_test_dataset.csv", delimiter=',', skiprows=1) # skip table head
g = np.linspace(-0.1, 0.5, num=input_size) # return evenly spaced array over interval

Array Attributes

a.dtype=np.int64,np.float64,np.object
****a.astype(int)

len(array)=array.size=4, 
sum(array)=array.sum()=10, 
np.average(array)=array.mean()=2.5
array.item(2)=3
A.ndim # = the number of dimensions

Array Shape

a.shape=(2,3) # shape->tuple
a = np.arange(6).Z(3, 2)  # a = [ [0, 1],
                          #       [2, 3],
                          #       [4, 5] ]
A.transpose(0, 2, 1) # permute
# swap last two dimensions
# or transpose((0, 2, 1))
np.arange(3).T == np.arange(3)

a = np.arange(1000).reshape(10, 10, 10)
print(a[3:5, ...].shape)  # We can use ... to select all other dimensions
a = a.reshape(20, -1) # -1: let numpy compute
grey_image[..., np.newaxis] # hidden resharp

np.ravel(a) # Return a contiguous flattened array.

a = np.arange(4)
	a[:, np.newaxis, np.newaxis, np.newaxis].shape == (4,1,1,1)

Array Indexing&Slicing

array indexing/slicing only gives shallow copy, while python list slicing gives deep copy

print(a[l,r]) #indexing, get [l,r)
a[-2:-3]=[] #empty
a[0,:].shape=(3,) # specific number->lower dimension 
a[0:1,:].shape=(1,3)
a[0][2]=a[0,2]

# integer array indexing
a = np.array([[1, 2], [3, 4], [5, 6]])
print(a[[0, 1, 2], [0, 1, 0]]) # Prints "[1 4 5]"
# same as print(np.array([a[0, 0], a[1, 1], a[2, 0]]))
>>> a = np.array([[1,2,3], [4,5,6], [7,8,9]])
>>> a[np.arange(len(a)), [1,0,2]]
array([2, 4, 9])

# boolean array indexing
b=(a>2) #a boolean array
a[b]=a[a>2]=[.., .., ..]
np.logical_or(boolean_array1, boolean_array2)

np.flatnonzero(a)==np.nonzero(np.ravel(a))[0]

a = np.arange(6).reshape(2,3) + 10
ind = np.unravel_index(np.argmax(a, axis=None), a.shape)
ind == (1,2)

Array Math

#elementwise, between same size arrays
array=array+1 
array=array**2 #to all elements
array1+=array2

# Vector
# rank-1 array in one row, but may be regarded as one column vector
# which makes life easier

np.dot(A,B) or A.dot(B) or A@B # Matrix Multiplication
A.T # Matrix Transpose(attribute)

Function

np.tile(A,(a,b)) #->enlarge a*b times
np.sum( welcome.column('hours sleep') >= 8 ) # welcome is a table in datascience library
np.sum(A,axis=0) #compute sum for each row(dimension 0)

Boardcasting