|
| 1 | +--- |
| 2 | +Title: '.all()' |
| 3 | +Description: 'Returns True if all elements in the array evaluate to True, or along a specified axis.' |
| 4 | +Subjects: |
| 5 | + - 'Computer Science' |
| 6 | + - 'Data Science' |
| 7 | +Tags: |
| 8 | + - 'Arrays' |
| 9 | + - 'Data Structures' |
| 10 | + - 'Methods' |
| 11 | + - 'NumPy' |
| 12 | +CatalogContent: |
| 13 | + - 'learn-python-3' |
| 14 | + - 'paths/data-science' |
| 15 | +--- |
| 16 | + |
| 17 | +In NumPy, the **`.all()`** method returns `True` if all elements in an ndarray evaluate to `True`, or if all elements along a specified axis evaluate to `True`. |
| 18 | + |
| 19 | +The `.all()` method can operate on the entire array to check if all values are truthy, or work along specific axes to perform row-wise or column-wise boolean validation. It follows Python's truth value testing conventions where non-zero numbers, non-empty arrays, and `True` values are considered truthy, while zero, empty arrays, `None`, and `False` are considered falsy. This method is particularly useful in data validation, filtering operations, and quality control checks in data science workflows. |
| 20 | + |
| 21 | +## Syntax |
| 22 | + |
| 23 | +```pseudo |
| 24 | +ndarray.all(axis=None, out=None, keepdims=False, where=True) |
| 25 | +``` |
| 26 | + |
| 27 | +**Parameters:** |
| 28 | + |
| 29 | +- `axis` (optional): Specifies the axis or axes along which to perform the logical AND operation. |
| 30 | + - If `None` (default), the test is applied to all elements in the array. |
| 31 | + - If integer, checks along that specific axis. |
| 32 | + - If tuple of integers, checks along multiple axes. |
| 33 | +- `out` (optional): Alternative output array to store the result. Must have the same shape as the expected output. |
| 34 | +- `keepdims` (optional): If `True`, the reduced axes are retained in the result as dimensions with size one. If `False` (default), the axes are removed from the result. |
| 35 | +- `where` (optional): Boolean array indicating which elements to include in the check. Elements where the condition is `False` are ignored and assumed to be `True`. |
| 36 | + |
| 37 | +**Return value:** |
| 38 | + |
| 39 | +Returns a boolean or ndarray of booleans, depending on the `axis` argument: |
| 40 | + |
| 41 | +- A single `bool` if the check is performed on the entire array. |
| 42 | +- An `ndarray` of `bool` values if performed along a specific axis. |
| 43 | + |
| 44 | +## Example 1: Basic Boolean Validation |
| 45 | + |
| 46 | +This example demonstrates using `.all()` to validate boolean conditions across an array: |
| 47 | + |
| 48 | +```py |
| 49 | +import numpy as np |
| 50 | + |
| 51 | +# Create arrays with different boolean patterns |
| 52 | +all_true = np.array([True, True, True, True]) |
| 53 | +has_false = np.array([True, True, False, True]) |
| 54 | +all_positive = np.array([1, 5, 3, 7]) |
| 55 | +has_zero = np.array([1, 5, 0, 7]) |
| 56 | + |
| 57 | +print("All True array:", all_true.all()) |
| 58 | +print("Array with False:", has_false.all()) |
| 59 | +print("All positive numbers:", all_positive.all()) |
| 60 | +print("Array with zero:", has_zero.all()) |
| 61 | + |
| 62 | +# Using comparison operators |
| 63 | +data = np.array([85, 92, 78, 95, 88]) |
| 64 | +all_passing = (data >= 70).all() |
| 65 | +all_excellent = (data >= 90).all() |
| 66 | + |
| 67 | +print(f"\nAll scores >= 70: {all_passing}") |
| 68 | +print(f"All scores >= 90: {all_excellent}") |
| 69 | +``` |
| 70 | + |
| 71 | +The output of this code is: |
| 72 | + |
| 73 | +```shell |
| 74 | +All True array: True |
| 75 | +Array with False: False |
| 76 | +All positive numbers: True |
| 77 | +Array with zero: False |
| 78 | + |
| 79 | +All scores >= 70: True |
| 80 | +All scores >= 90: False |
| 81 | +``` |
| 82 | + |
| 83 | +This example shows how `.all()` evaluates different types of arrays. Non-zero numbers are considered truthy, while zero and `False` values cause the method to return `False`. |
| 84 | + |
| 85 | +## Example 2: Axis-wise Validation in Multi-dimensional Arrays |
| 86 | + |
| 87 | +This example demonstrates how to validate conditions along specific axes in a 2D array: |
| 88 | + |
| 89 | +```py |
| 90 | +import numpy as np |
| 91 | + |
| 92 | +# Create a 2D array of test results (pass=1, fail=0) |
| 93 | +test_results = np.array([ |
| 94 | + [1, 1, 1, 1], # Student 1: All passed |
| 95 | + [1, 1, 0, 1], # Student 2: One failure |
| 96 | + [1, 1, 1, 1], # Student 3: All passed |
| 97 | + [1, 0, 1, 1] # Student 4: One failure |
| 98 | +]) |
| 99 | + |
| 100 | +print("Test results (1=pass, 0=fail):") |
| 101 | +print(test_results) |
| 102 | + |
| 103 | +# Check if all students passed each test (column-wise) |
| 104 | +all_passed_per_test = test_results.all(axis=0) |
| 105 | +print(f"\nAll students passed each test: {all_passed_per_test}") |
| 106 | + |
| 107 | +# Check if each student passed all tests (row-wise) |
| 108 | +all_passed_per_student = test_results.all(axis=1) |
| 109 | +print(f"Each student passed all tests: {all_passed_per_student}") |
| 110 | + |
| 111 | +# Check if all students passed all tests (entire array) |
| 112 | +perfect_class = test_results.all() |
| 113 | +print(f"Perfect class (all passed): {perfect_class}") |
| 114 | +``` |
| 115 | + |
| 116 | +The output of this code is: |
| 117 | + |
| 118 | +```shell |
| 119 | +Test results (1=pass, 0=fail): |
| 120 | +[[1 1 1 1] |
| 121 | + [1 1 0 1] |
| 122 | + [1 1 1 1] |
| 123 | + [1 0 1 1]] |
| 124 | + |
| 125 | +All students passed each test: [ True False False True] |
| 126 | +Each student passed all tests: [ True False True False] |
| 127 | +Perfect class (all passed): False |
| 128 | +``` |
| 129 | + |
| 130 | +This example shows how the `axis` parameter controls the direction of validation. Using `axis=0` checks columns (tests), while `axis=1` checks rows (students). |
| 131 | + |
| 132 | +## Example 3: Data Quality Validation with `keepdims` |
| 133 | + |
| 134 | +This example shows how to use `.all()` with `keepdims` for data quality checks that maintain array dimensions: |
| 135 | + |
| 136 | +```py |
| 137 | +import numpy as np |
| 138 | + |
| 139 | +# Create sensor data with some readings potentially out of range |
| 140 | +sensor_data = np.array([ |
| 141 | + [45, 52, 48, 51], |
| 142 | + [46, 49, 47, 50], |
| 143 | + [44, 53, 46, 49] |
| 144 | +]) |
| 145 | + |
| 146 | +print("Sensor readings:") |
| 147 | +print(sensor_data) |
| 148 | + |
| 149 | +# Define valid range (40-55) |
| 150 | +min_valid = 40 |
| 151 | +max_valid = 55 |
| 152 | + |
| 153 | +# Check if all readings per sensor are within range |
| 154 | +within_range = (sensor_data >= min_valid) & (sensor_data <= max_valid) |
| 155 | +all_valid_per_sensor = within_range.all(axis=1, keepdims=True) |
| 156 | + |
| 157 | +print(f"\nAll readings valid per sensor:\n{all_valid_per_sensor}") |
| 158 | +print(f"Shape: {all_valid_per_sensor.shape}") |
| 159 | + |
| 160 | +# Create a quality report |
| 161 | +quality_report = np.where(all_valid_per_sensor, "PASS", "FAIL") |
| 162 | +print(f"\nQuality report:\n{quality_report}") |
| 163 | +``` |
| 164 | + |
| 165 | +The output of this code is: |
| 166 | + |
| 167 | +```shell |
| 168 | +Sensor readings: |
| 169 | +[[45 52 48 51] |
| 170 | + [46 49 47 50] |
| 171 | + [44 53 46 49]] |
| 172 | + |
| 173 | +All readings valid per sensor: |
| 174 | +[[ True] |
| 175 | + [ True] |
| 176 | + [ True]] |
| 177 | +Shape: (3, 1) |
| 178 | + |
| 179 | +Quality report: |
| 180 | +[['PASS'] |
| 181 | + ['PASS'] |
| 182 | + ['PASS']] |
| 183 | +``` |
| 184 | + |
| 185 | +The `keepdims=True` parameter maintains array dimensions, making it easier to combine validation results with other operations or create aligned reports. |
| 186 | + |
| 187 | +## Codebyte Example: Using the `where` Parameter for Conditional Validation |
| 188 | + |
| 189 | +This example demonstrates selective validation using the `where` parameter: |
| 190 | + |
| 191 | +```codebyte/python |
| 192 | +import numpy as np |
| 193 | +
|
| 194 | +# Create an array of product inventory status |
| 195 | +# Positive = in stock, Negative = discontinued, Zero = out of stock |
| 196 | +inventory = np.array([ |
| 197 | + [25, -1, 15, 30], |
| 198 | + [40, 22, -1, 18], |
| 199 | + [0, 35, 28, -1] |
| 200 | +]) |
| 201 | +
|
| 202 | +print("Inventory (positive=in stock, negative=discontinued, 0=out):") |
| 203 | +print(inventory) |
| 204 | +
|
| 205 | +# Check if all active products (non-negative) are in stock (non-zero) |
| 206 | +active_mask = inventory >= 0 |
| 207 | +all_active_in_stock = (inventory > 0).all(where=active_mask) |
| 208 | +print(f"\nAll active products in stock: {all_active_in_stock}") |
| 209 | +
|
| 210 | +# Check per row if all active products are in stock |
| 211 | +all_in_stock_per_row = (inventory > 0).all(axis=1, where=active_mask, keepdims=True) |
| 212 | +print(f"All active products in stock per row:\n{all_in_stock_per_row}") |
| 213 | +``` |
| 214 | + |
| 215 | +The `where` parameter allows selective validation, ignoring certain elements (like discontinued products) when checking conditions. |
0 commit comments