4.12. Array Rounding

4.12.1. Floor

import numpy as np


a = np.array([1., 1.00000001, 1.99999999])

np.floor(a)
# array([1., 1., 1.])

4.12.2. Ceil

import numpy as np


a = np.array([1., 1.00000001, 1.99999999])

np.ceil(a)
# array([1., 2., 2.])

4.12.3. Round

  • Round elements of the array to the nearest integer.

  • There is no np.round() method

  • Only np.rint()

import numpy as np


a = np.array([1., 1.00000001, 1.99999999])

np.rint(a)
# array([1., 1., 2.])

4.12.4. Clip

  • Increase smaller values to lower bound

  • Decrease higher values to upper bound

import numpy as np


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

a.clip(2, 5)
# array([2, 2, 3])
import numpy as np


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

a.clip(2, 5)
# array([[2, 2, 3],
#        [4, 5, 5]])
import numpy as np


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

a.clip(2, 5)
# array([[2, 2, 3],
#        [4, 5, 5],
#        [5, 5, 5]])
import numpy as np


a = np.array([[-2, -1, 0],
              [0, 1, 2]])


a.astype(bool)
# array([[ True,  True, False],
#        [False,  True,  True]])

a.clip(0, 1)
# array([[0, 0, 0],
#        [0, 1, 1]])

a.clip(0, 1).astype(bool)
# array([[False, False, False],
#        [False,  True,  True]])

4.12.5. Assignments

4.12.5.1. Numpy Clip

  • Complexity level: medium

  • Lines of code to write: 3 lines

  • Estimated time of completion: 5 min

  • Solution: solution/numpy_clip.py

English
  1. Set random seed to zero

  2. Generate result: ndarray of 21 random integers from 0 to 100 (exclusive)

  3. Change shape to 7x3

  4. Clip numbers only in first column to 50 (inclusive) to 80 (exclusive)

  5. Print result

  6. Compare result with "Output" section (see below)

Polish
  1. Ustaw ziarno losowości na zero

  2. Wygeneruj result: ndarray z 21 losowymi liczbami całkowitymi od 0 do 100 (rozłącznie)

  3. Zmień kształt na 7x3

  4. Przytnij liczby w pierwszej kolumnie od 50 (włącznie) do 80 (rozłącznie)

  5. Wypisz result

  6. Porównaj wyniki z sekcją "Output" (patrz poniżej)

Output
a: ndarray
# array([[50, 47, 64],
#        [67, 67,  9],
#        [79, 21, 36],
#        [79, 70, 88],
#        [79, 12, 58],
#        [65, 39, 87],
#        [50, 88, 81]])