Comparaciones, máscaras y lógica booleana
Ejemplo: Contando días¶
import numpy as np
import pandas as pd
# use pandas to extract rainfall inches as a NumPy array
rainfall = pd.read_csv('data/Seattle2014.csv')['PRCP'].values
inches = rainfall / 254.0 # 1/10mm -> inches
inches.shape
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn; seaborn.set() # set plot styles
plt.hist(inches, 40);
Operadores de comparación como ufuncs¶
En Cálculos con Arrays 1. Ufuncs introducimos ufuncs en particular operadores aritméticos
+
,-
,*
,/
, y otrosNumPy implementa operadores de comparación
<
(menor que) y>
(mayor que)
x = np.array([1, 2, 3, 4, 5])
x < 3 # less than
x > 3 # greater than
x <= 3 # less than or equal
x >= 3 # greater than or equal
x != 3 # not equal
x == 3 # equal
(2 * x) == (x ** 2)
As in the case of arithmetic operators, the comparison operators are implemented as ufuncs in NumPy; for example, when you write x < 3
, internally NumPy uses np.less(x, 3)
.
A summary of the comparison operators and their equivalent ufunc is shown here:
Operator | Equivalent ufunc | Operator | Equivalent ufunc | |
---|---|---|---|---|
== |
np.equal |
!= |
np.not_equal |
|
< |
np.less |
<= |
np.less_equal |
|
> |
np.greater |
>= |
np.greater_equal |
rng = np.random.RandomState(0)
x = rng.randint(10, size=(3, 4))
x
x < 6
Usando Arrays Booleanos¶
print(x)
Contando entradas¶
# how many values less than 6?
np.count_nonzero(x < 6)
np.sum(x < 6)
# how many values less than 6 in each row?
np.sum(x < 6, axis=1)
# are there any values greater than 8?
np.any(x > 8)
# are there any values less than zero?
np.any(x < 0)
# are all values less than 10?
np.all(x < 10)
# are all values equal to 6?
np.all(x == 6)
np.all
and np.any
can be used along particular axes as well. For example:
# are all values in each row less than 8?
np.all(x < 8, axis=1)
Operadores Booleanos¶
np.sum((inches > 0.5) & (inches < 1))
np.sum(~( (inches <= 0.5) | (inches >= 1) ))
Operator | Equivalent ufunc | Operator | Equivalent ufunc | |
---|---|---|---|---|
& |
np.bitwise_and |
| | np.bitwise_or |
|
^ |
np.bitwise_xor |
~ |
np.bitwise_not |
print("Number days without rain: ", np.sum(inches == 0))
print("Number days with rain: ", np.sum(inches != 0))
print("Days with more than 0.5 inches:", np.sum(inches > 0.5))
print("Rainy days with < 0.2 inches :", np.sum((inches > 0) &
(inches < 0.2)))
Máscaras de Arrays Booleanos¶
x
x < 5
x[x < 5]
# construct a mask of all rainy days
rainy = (inches > 0)
# construct a mask of all summer days (June 21st is the 172nd day)
days = np.arange(365)
summer = (days > 172) & (days < 262)
print("Median precip on rainy days in 2014 (inches): ",
np.median(inches[rainy]))
print("Median precip on summer days in 2014 (inches): ",
np.median(inches[summer]))
print("Maximum precip on summer days in 2014 (inches): ",
np.max(inches[summer]))
print("Median precip on non-summer rainy days (inches):",
np.median(inches[rainy & ~summer]))
Usar las palabras reservadas and
/or
contra usar los operadores &
/|
¶
bool(42), bool(0)
bool(42 and 0)
bool(42 or 0)
bin(42)
bin(59)
bin(42 & 59)
bin(42 | 59)
A = np.array([1, 0, 1, 0, 1, 0], dtype=bool)
B = np.array([1, 1, 1, 0, 1, 1], dtype=bool)
A | B
A or B
x = np.arange(10)
(x > 4) & (x < 8)
(x > 4) and (x < 8)