Numpy

Load NumPy

import numpy as np

NumPY basics

a = np.array([1,2,3], dtype=np.int8)
print(a)
[1 2 3]
b = np.array([[9.0,8.0,7.0],[6.0,5.0,4.0]], dtype=np.float32)
print(b)
[[9. 8. 7.]
 [6. 5. 4.]]
a.ndim ## get dimension
1
b.shape # get shape
(2, 3)
b.dtype # get type
dtype('float32')
b.itemsize # get size
4
b.size # get total number of elements
6
a.nbytes # get total size
3
c = np.array([[1,2,3,4,5,6,7],[8,9,10,11,12,13,14]])
print(c)
[[ 1  2  3  4  5  6  7]
 [ 8  9 10 11 12 13 14]]
c[1,5] # get element [row, column]
13
c[0,:] # get a specific row
array([1, 2, 3, 4, 5, 6, 7])
c[:,2] # get a specific column
array([ 3, 10])
c[0,1:6:2] # extract specific items [startindex:endindex:stepsize]
array([2, 4, 6])
c[1,5] = 20 # change an element
print(c)
[[ 1  2  3  4  5  6  7]
 [ 8  9 10 11 12 20 14]]
c[:,2] = 5 # change all values in a column
print(c)
[[ 1  2  5  4  5  6  7]
 [ 8  9  5 11 12 20 14]]
c[:,1] = [1,2] # change all values in a column
print(c)
[[ 1  1  5  4  5  6  7]
 [ 8  2  5 11 12 20 14]]
d = np.array([[[1,2],[3,4]],[[5,6],[7,8]]]) # 3D array
print(d)
[[[1 2]
  [3 4]]

 [[5 6]
  [7 8]]]
d[0,1,1] # get specific element
4
d[:,1,:] # get specific elements
array([[3, 4],
       [7, 8]])
d[:,1,:] = [[9,9],[8,8]] # replace
print(d)
[[[1 2]
  [9 9]]

 [[5 6]
  [8 8]]]

Initialize different types of arrays

np.zeros((2,3)) ## all 0s matrix
array([[0., 0., 0.],
       [0., 0., 0.]])
np.ones((4,2,2), dtype='int8') ## all 1s matrix
array([[[1, 1],
        [1, 1]],

       [[1, 1],
        [1, 1]],

       [[1, 1],
        [1, 1]],

       [[1, 1],
        [1, 1]]], dtype=int8)
np.full((2,2), 99, dtype='float32') ## any other number
array([[99., 99.],
       [99., 99.]], dtype=float32)
np.full(c.shape, 4, dtype='int8') ## any other number
array([[4, 4, 4, 4, 4, 4, 4],
       [4, 4, 4, 4, 4, 4, 4]], dtype=int8)
np.random.rand(4,2) # random array of floats
array([[0.11760296, 0.32738002],
       [0.41965836, 0.7270041 ],
       [0.5702633 , 0.14680373],
       [0.79868021, 0.07875023]])
np.random.random_sample(d.shape) # random array of floats like other shape
array([[[0.81856157, 0.38074572],
        [0.15777699, 0.18581494]],

       [[0.55835552, 0.14995853],
        [0.92941754, 0.11767722]]])
np.random.randint(7, size=(3,3)) # random array of integers [0-7)
array([[0, 4, 4],
       [3, 0, 6],
       [0, 1, 5]])
np.random.randint(4, 8, size=(3,3)) # random array of integers [4-8)
array([[4, 5, 6],
       [7, 6, 6],
       [6, 6, 7]])
np.identity(3) # the identity matrix
array([[1., 0., 0.],
       [0., 1., 0.],
       [0., 0., 1.]])
arr = np.array([[1,2,3]])
r1 = np.repeat(arr, 3, axis=0) # repeat array
print(r1)
[[1 2 3]
 [1 2 3]
 [1 2 3]]
# solving a problem
x = np.ones((5,5))
x[1:4,1:4] = 0
x[2,2] = 9
print(x)
[[1. 1. 1. 1. 1.]
 [1. 0. 0. 0. 1.]
 [1. 0. 9. 0. 1.]
 [1. 0. 0. 0. 1.]
 [1. 1. 1. 1. 1.]]
# solving a problem alt
x = np.ones((5,5))
z = np.zeros((3,3))
z[1,1] = 9
x[1:-1,1:-1] = z
print(x)
[[1. 1. 1. 1. 1.]
 [1. 0. 0. 0. 1.]
 [1. 0. 9. 0. 1.]
 [1. 0. 0. 0. 1.]
 [1. 1. 1. 1. 1.]]

Copying arrays

a = np.array([1,2,3])
b = a # pointing to the same array
b[0] = 100
print(a)
print(b)
[100   2   3]
[100   2   3]
a = np.array([1,2,3])
b = a.copy() # pointing to a different array
b[0] = 100
print(a)
print(b)
[1 2 3]
[100   2   3]

Math

a = np.array([1,2,3,4])
print(a)
[1 2 3 4]
a + 2 # broadcasting a scalar to array
array([3, 4, 5, 6])
a - 1
array([0, 1, 2, 3])
a * 2
array([2, 4, 6, 8])
a / 2
array([0.5, 1. , 1.5, 2. ])
b = a - 1
print(b)
[0 1 2 3]
c = a + b # add two arrays
print(c)
[1 3 5 7]
np.sin(a) # take the sine of array elementwise
array([ 0.84147098,  0.90929743,  0.14112001, -0.7568025 ])

Linear algebra

a = np.ones((2,3))
b = np.full((3,2), 2)
print(a)
print(b)
[[1. 1. 1.]
 [1. 1. 1.]]
[[2 2]
 [2 2]
 [2 2]]
np.matmul(a,b)
array([[6., 6.],
       [6., 6.]])
c = np.identity(3)
print(c)
[[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]]
np.linalg.det(c) # find the determinant
1.0

Statistics

stats = np.array([[1,2,3],[4,5,6]])
stats
array([[1, 2, 3],
       [4, 5, 6]])
np.min(stats, axis=0)
array([1, 2, 3])
np.max(stats)
6
np.sum(stats, axis=0)
array([5, 7, 9])

Reorganizing arrays

before = np.array([[1,2,3,4],[5,6,7,8]])
print(before)
[[1 2 3 4]
 [5 6 7 8]]
print(before.shape)
(2, 4)
after = before.reshape((2,2,2))
print(after)
[[[1 2]
  [3 4]]

 [[5 6]
  [7 8]]]
print(before.transpose())
[[1 5]
 [2 6]
 [3 7]
 [4 8]]
print(before)
array([[1, 2, 3, 4],
       [5, 6, 7, 8]])
# vertically stacking vectors
v1 = np.array([1,2,3,4])
v2 = np.array([5,6,7,8])
np.vstack([v1,v2,v1])
array([[1, 2, 3, 4],
       [5, 6, 7, 8],
       [1, 2, 3, 4]])
# horizontally stacking vectors
h1 = np.array([1,2,3])
h2 = np.array([4,5,6])
np.hstack([h1,h2,h1])
array([1, 2, 3, 4, 5, 6, 1, 2, 3])

Miscellaneous

# load data from a file
filedata = np.genfromtxt('data.txt', delimiter=',', dtype='float32')
filedata = filedata.astype('int16') # change data type
print(filedata)
[[ 1  2  3  4  5]
 [ 6  7  8  9 10]
 [11 12 13 14 15]]
# boolean msaking and advanced indexing
filedata > 7
array([[False, False, False, False, False],
       [False, False,  True,  True,  True],
       [ True,  True,  True,  True,  True]])
filedata[filedata > 8]
array([ 9, 10, 11, 12, 13, 14, 15], dtype=int16)
# indexing with a list
a = np.array([1,2,3,4,5,6,7,8,9])
a[[1,2,8]]
array([2, 3, 9])
np.any(filedata > 12, axis=0) # any value in columns > 12
array([False, False,  True,  True,  True])
np.all(filedata > 3, axis=0)  # all values in columns > 3
array([False, False, False,  True,  True])
b = (filedata > 5) & (filedata < 10)
print(b)
[[False False False False False]
 [ True  True  True  True False]
 [False False False False False]]
b.dtype
dtype('bool')
# problem
mx = np.arange(1, 31, dtype='int8')
mx = mx.reshape((6,5))
print(mx)
[[ 1  2  3  4  5]
 [ 6  7  8  9 10]
 [11 12 13 14 15]
 [16 17 18 19 20]
 [21 22 23 24 25]
 [26 27 28 29 30]]
mx[2:4,:2]
array([[11, 12],
       [16, 17]], dtype=int8)
[mx[k,k+1] for k in range(4)]
[2, 8, 14, 20]
mx[[0,1,2,3],[1,2,3,4]]
array([ 2,  8, 14, 20], dtype=int8)
mx[[0,4,5],-2:]
array([[ 4,  5],
       [24, 25],
       [29, 30]], dtype=int8)

Source: Python NumPy Tutorial for Beginners