Numpy

Cheatsheet

Basic Numpy

import numpy as np
Copy to clipboard

Create array

# empty array np.empty(<shape>)
np.empty((3,2))
Copy to clipboard
array([[4.64967835e-310, 0.00000000e+000],
       [0.00000000e+000, 0.00000000e+000],
       [0.00000000e+000, 0.00000000e+000]])
Copy to clipboard
# np.linspace(start, stop, len)
# similar to R: seq(from, to, by)
print(
    np.linspace(1, 5, 5),
    np.linspace(1, 5, 3),
    sep = '\n')
Copy to clipboard
[1. 2. 3. 4. 5.]
[1. 3. 5.]
Copy to clipboard
# np.arange(start, stop, step)
# equivalent to R: seq(from, to, by)
print(
    np.arange(5),        # stop
    np.arange(1, 5),     # start, stop
    np.arange(1, 6, 2),  # start, stop, step
    sep = '\n'
)
Copy to clipboard
[0 1 2 3 4]
[1 2 3 4]
[1 3 5]
Copy to clipboard
# random array
print(
    np.random.rand(),
    np.random.rand(3, 5),
    np.random.rand(3, 5, 1),
    sep = '\n\n'
)
Copy to clipboard
0.1243342257052763

[[0.37067402 0.52523751 0.64556949 0.20251635 0.31186591]
 [0.76393491 0.71054838 0.38912143 0.41679623 0.58198636]
 [0.2743352  0.02532827 0.82378454 0.84843088 0.3390712 ]]

[[[0.98378478]
  [0.29438406]
  [0.23131775]
  [0.84617288]
  [0.38511699]]

 [[0.13675279]
  [0.75574176]
  [0.15372809]
  [0.73705805]
  [0.73187824]]

 [[0.10777166]
  [0.34323938]
  [0.66599043]
  [0.58093256]
  [0.27132764]]]
Copy to clipboard
# create array from tuple or list
a = np.array([(1,2,3), 
              (4,5,6)],
             dtype = float)
print(a)
print(type(a), type(a[0,0]))
Copy to clipboard
[[1. 2. 3.]
 [4. 5. 6.]]
<class 'numpy.ndarray'> <class 'numpy.float64'>
Copy to clipboard

Changing Shape

print(a.shape)
a.shape = (3, 2)
print(a.shape)
a
Copy to clipboard
(2, 3)
(3, 2)
Copy to clipboard
array([[1., 2.],
       [3., 4.],
       [5., 6.]])
Copy to clipboard

Common Functions

Arithmetic

a = np.array([1,2,3], dtype=float)
b = np.array([4,5,6], dtype=float)
print(
    a + b,
    a / b,
    a * 3,
    a.dot(b),  # dot product
    a @ b,     # dot product
    np.sin(a),
    sep = '\n\n')
Copy to clipboard
[5. 7. 9.]

[0.25 0.4  0.5 ]

[3. 6. 9.]

32.0

32.0

[0.84147098 0.90929743 0.14112001]
Copy to clipboard

Logarithm & Exponential

Numpy doesn’t have log function for arbitrary base, so use the rule: logba=logxalogxb.

# log with base 2
np.isclose(
    np.log2(a), np.log(a)/np.log(2)
)
Copy to clipboard
array([ True,  True,  True])
Copy to clipboard
print(
    np.e,
    np.exp([0, 1, 2]),
    np.isclose(np.e, np.exp(1)),
    sep = '\n'
)
Copy to clipboard
2.718281828459045
[1.         2.71828183 7.3890561 ]
True
Copy to clipboard

Aggregate Functions

a = np.array([(1,2,3),
              (4,5,6)])

print(
    a.shape,
    a.sum(),        # all elements
    a.sum(axis=0),  # column wise
    a.sum(axis=1),  # row wise
    sep='\n'
)
Copy to clipboard
(2, 3)
21
[5 7 9]
[ 6 15]
Copy to clipboard
print(
    np.median(a),
    np.median(a, axis=0),
    np.cumsum(a),
    sep = '\n'
)
Copy to clipboard
3.5
[2.5 3.5 4.5]
[ 1  3  6 10 15 21]
Copy to clipboard

Modify Array

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

idx, = np.where(a == 1)  # np.where returns a tuple when only condition provided
print(idx)

a = np.delete(a, idx)
a
Copy to clipboard
[0 3]
Copy to clipboard
array([2, 3, 4])
Copy to clipboard
a = np.array([1, 2, 3, 1, 4])

idx = np.where(a == 1, True, False)
print(idx)

b = a[~idx]
b
Copy to clipboard
[ True False False  True False]
Copy to clipboard
array([2, 3, 4])
Copy to clipboard

Image processing with matplotlib & numpy

%matplotlib inline
from matplotlib.image import imread
import matplotlib.pyplot as plt

img = imread('/home/liao/img/bg/road-straight.jpg')
plt.imshow(img)
Copy to clipboard
<matplotlib.image.AxesImage at 0x7feae949bf10>
Copy to clipboard
../_images/numpy_25_1.png
img.shape
Copy to clipboard
(1280, 1920, 3)
Copy to clipboard
img[::, ::, ::] == img
Copy to clipboard
array([[[ True,  True,  True],
        [ True,  True,  True],
        [ True,  True,  True],
        ...,
        [ True,  True,  True],
        [ True,  True,  True],
        [ True,  True,  True]],

       [[ True,  True,  True],
        [ True,  True,  True],
        [ True,  True,  True],
        ...,
        [ True,  True,  True],
        [ True,  True,  True],
        [ True,  True,  True]],

       [[ True,  True,  True],
        [ True,  True,  True],
        [ True,  True,  True],
        ...,
        [ True,  True,  True],
        [ True,  True,  True],
        [ True,  True,  True]],

       ...,

       [[ True,  True,  True],
        [ True,  True,  True],
        [ True,  True,  True],
        ...,
        [ True,  True,  True],
        [ True,  True,  True],
        [ True,  True,  True]],

       [[ True,  True,  True],
        [ True,  True,  True],
        [ True,  True,  True],
        ...,
        [ True,  True,  True],
        [ True,  True,  True],
        [ True,  True,  True]],

       [[ True,  True,  True],
        [ True,  True,  True],
        [ True,  True,  True],
        ...,
        [ True,  True,  True],
        [ True,  True,  True],
        [ True,  True,  True]]])
Copy to clipboard

Modify Image: Compression

Compress image by cutting the resolution to half, i.e. subset every two rows and every two columns in ndarray.

plt.imshow(img[::2, ::2, :])
Copy to clipboard
<matplotlib.image.AxesImage at 0x7feae7c1db50>
Copy to clipboard
../_images/numpy_29_1.png

Modify Image: Color Mask

# np.where(<cond>, <value for True>, <value for False>)
img_mask = np.where(img > 180, 255, img)
plt.imshow(img_mask)
Copy to clipboard
<matplotlib.image.AxesImage at 0x7feae7b8ecd0>
Copy to clipboard
../_images/numpy_31_1.png
# np.where(<cond>, <value for True>, <value for False>)
img_mask = np.where(img < 80, 0, img)
plt.imshow(img_mask)
Copy to clipboard
<matplotlib.image.AxesImage at 0x7feae7b01b10>
Copy to clipboard
../_images/numpy_32_1.png