4.13. Array Rounding

4.13.1. Floor

import numpy as np


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

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

4.13.2. Ceil

import numpy as np


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

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

4.13.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.13.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]])

4.13.5. Assignments

4.13.5.1. Clip

  • Complexity level: easy

  • Lines of code to write: 3 lines

  • Estimated time of completion: 5 min

  • Filename: solution/numpy_clip.py

English
  1. Set random seed to zero

  2. Generate a: 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 a

Polish
  1. Ustaw ziarno losowości na zero

  2. Wygeneruj a: 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 a

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]])