761 words
4 minutes
NumPy Logical Operations

IX. NumPy Logical Operations (逻辑运算)#

Logical operations (逻辑运算) in NumPy work element-wise on arrays and always return a boolean array (布尔数组). These are the foundation of masking (掩码) and conditional filtering (条件筛选).

1. Comparison Operators (比较运算符)#

Core idea: Compare each element to a value or to another array. Returns True/False for each position.

import numpy as np
a = np.array([1, 2, 3, 4, 5])
a > 3 # [False False False True True]
a == 3 # [False False True False False]
a != 3 # [ True True False True True]
a >= 3 # [False False True True True]
# Functional equivalents (函数式写法)
np.greater(a, 3) # same as a > 3
np.less(a, 3) # same as a < 3
np.equal(a, 3) # same as a == 3
np.not_equal(a, 3) # same as a != 3
Note: Never use Python's `and` / `or` / `not` on arrays — they raise errors. Always use np.logical_and / logical_or / logical_not instead.

2. Logical AND / OR / NOT (逻辑与/或/非)#

Core idea: Combine boolean arrays element-wise. Use &, |, ~ as shorthand.

a = np.array([1, 2, 3, 4, 5])
# AND (与): both conditions must be True
mask = (a > 2) & (a < 5) # [F F T T F]
np.logical_and(a > 2, a < 5) # same
# OR (或): at least one condition is True
mask = (a < 2) | (a > 4) # [T F F F T]
np.logical_or(a < 2, a > 4) # same
# NOT (非): invert boolean
mask = ~(a > 3) # [T T T F F]
np.logical_not(a > 3) # same
Note: Always wrap individual conditions in parentheses when using & and |, because & has higher precedence than > in Python. E.g., write (a > 2) & (a < 5), not a > 2 & a < 5.

3. Boolean Masking — Filter Arrays (布尔掩码筛选)#

Core idea: Use a boolean array as an index to select matching elements.

a = np.array([10, 25, 3, 47, 8, 60])
mask = a > 20
print(mask) # [False True False True False True]
print(a[mask]) # [25 47 60] — only values where mask is True
# One-liner
a[a > 20] # [25 47 60]
a[(a > 10) & (a < 50)] # [25 47]

4. np.where() — Conditional Selection (条件选择)#

Core idea: Like a vectorized ternary: where(condition, value_if_true, value_if_false).

a = np.array([1, -2, 3, -4, 5])
np.where(a > 0, a, 0) # [1 0 3 0 5] — replace negatives with 0
np.where(a > 0, 'pos', 'neg') # ['pos' 'neg' 'pos' 'neg' 'pos']
# Without x, y: returns indices where condition is True (返回满足条件的索引)
np.where(a > 0) # (array([0, 2, 4]),)

5. any() / all() — Global Boolean Tests (全局布尔检验)#

Core idea: Test whether any or all elements satisfy a condition.

a = np.array([1, 2, 3, 4, 5])
np.any(a > 4) # True — at least one element > 4
np.all(a > 0) # True — all elements > 0
np.all(a > 3) # False — not all > 3
# With axis
m = np.array([[1, 2], [0, 4]])
np.any(m == 0, axis=1) # [False True]

6. isnan() / isinf() — Special Value Checks (特殊值检验)#

a = np.array([1.0, np.nan, np.inf, -np.inf, 2.0])
np.isnan(a) # [F T F F F]
np.isinf(a) # [F F T T F]
np.isfinite(a) # [T F F F T]
# Clean NaN values (清除NaN值)
a[~np.isnan(a)] # [1. inf -inf 2.]

7. Quick Comparison Table#

Operation (操作)ShorthandFunction
Greater than (大于)a > bnp.greater(a, b)
Less than (小于)a < bnp.less(a, b)
Equal (等于)a == bnp.equal(a, b)
AND (与)mask1 & mask2np.logical_and(m1, m2)
OR (或)`mask1mask2`
NOT (非)~masknp.logical_not(mask)
Conditional replacenp.where(cond, x, y)
Any true?np.any(cond)
All true?np.all(cond)
💡 One-line Takeaway
Build boolean masks with & / | / ~ (always use parentheses!), apply them for filtering, and use np.where() for conditional replacement.
NumPy Logical Operations
https://lxy-alexander.github.io/blog/posts/numpy/api/09numpy-logical-operations/
Author
Alexander Lee
Published at
2026-03-12
License
CC BY-NC-SA 4.0