Numpy3 Flashcards
a = np.array([0, 1, 2])
b = np.array([5, 5, 5])
a + b
array([5, 6, 7])
for arrays of the same size, binary operations are performed on an element-by-element basis
Rule 1: If the two arrays differ in their number of dimensions, the shape of the one with fewer dimensions is padded with ones on its leading (left) side.
Rule 2: If the shape of the two arrays does not match in any dimension, the array with shape equal to 1 in that dimension is stretched to match the other shape.
Rule 3: If in any dimension the sizes disagree and neither is equal to 1, an error is raised.
Rules of Broadcasting
np.newaxis
is used to increase the dimension of the existing array by one more dimension, when used once. Thus,
1D array will become 2D array
2D array will become 3D array
3D array will become 4D array
x = np.array([1, 2, 3, 4, 5])
x < 3
array([ True, True, False, False, False], dtype=bool)
(2 * x) == (x ** 2)
element-wise comparison of two arrays, and to include compound expressions
array([False, True, False, False, False], dtype=bool)
== np.equal != np.not_equal
< np.less <= np.less_equal
> np.greater >= np.greater_equal
comparison operators are implemented as ufuncs in NumPy
# how many values less than 6? #np.count_nonzero(x < 6) np.sum(inches >.1)
To count the number of True entries in a Boolean array, np.count_nonzero is useful:
np.sum(x < 6, axis=1)
how many values less than 6 in each row?
# are there any values greater than 8? np.any(x > 8)
quickly checking whether any or all the values are true
np.all(x < 10)
# are all values equal to 6? np.all(x == 6)
quickly checking whether any or all the values are true
np.sum((inches > 0.5) & (inches < 1))
bitwise logic operators, &, |, ^, and ~
& np.bitwise_and | np.bitwise_or
^ np.bitwise_xor ~ np.bitwise_not
bitwise Boolean operators and their equivalent ufuncs
“Number days without rain: “, np.sum(inches == 0))
“Number days with rain: “, np.sum(inches != 0))
“Days with more than 0.5 inches:”, np.sum(inches > 0.5))
“Rainy days with < 0.2 inches :”, np.sum((inches > 0) &
(inches < 0.2)))
bitwise Examples
x[x < 5]
to select these values from the array, we can simply index on this Boolean array; this is known as a masking operation
np.median(inches[rainy & ~summer]
Example operation