Table of Contents#
- Introduction
- Syntax and Parameters of
numpy.compress() - How
numpy.compress()Works - Example Usage
- Common Practices and Best Practices
- Use Cases
- Limitations and Considerations
- Conclusion
- References
Syntax and Parameters of numpy.compress()#
The syntax of numpy.compress() is:
numpy.compress(condition, a, axis=None, out=None)Parameters:#
condition: A 1-D array of booleans (or integers, where non-zero values are treated asTrue). This array determines which elements ofato keep.a: The input array (numpy.ndarray) from which elements are selected.axis(optional): The axis along which to apply thecondition. IfNone(default), the array is flattened before selection. For an n-dimensional array,axiscan be0(rows),1(columns), ...,n-1.out(optional): A pre-allocated array to store the result. Must have the same shape as the expected output (derived fromconditionandaxis).
How numpy.compress() Works#
numpy.compress() selects elements from a where condition is True (or non-zero). Here’s how it handles different scenarios:
- If
axis=None: The arrayais flattened (converted to 1D), andconditionmust have length equal to the number of elements ina. The output is a 1D array of selected elements. - If
axisis specified: Theconditionis applied along that axis. For example, ifaxis=0(rows in a 2D array),conditionmust have length equal to the number of rows. The output retains the original array’s dimensions, except the size alongaxisis reduced to the number ofTruevalues incondition.
Example Usage#
1D Array Example#
Filter elements from a 1D array using a boolean condition:
import numpy as np
# Input array
arr = np.array([10, 20, 30, 40, 50])
# Condition: select elements at indices 0, 2, 4 (0-based)
condition = np.array([True, False, True, False, True])
# Apply compress
compressed = np.compress(condition, arr)
print("Compressed 1D array:", compressed)
# Output: [10 30 50]2D Array with Axis=0 (Rows)#
Select rows from a 2D array where condition is True:
arr_2d = np.array([[1, 2],
[3, 4],
[5, 6]])
# Condition: select rows 0 and 2 (0-based)
condition = np.array([True, False, True])
# Apply compress along axis=0 (rows)
compressed_axis0 = np.compress(condition, arr_2d, axis=0)
print("Compressed along axis=0:")
print(compressed_axis0)
# Output:
# [[1 2]
# [5 6]]2D Array with Axis=1 (Columns)#
Select columns from a 2D array where condition is True:
# Condition: select column 0 (0-based)
condition_axis1 = np.array([True, False])
# Apply compress along axis=1 (columns)
compressed_axis1 = np.compress(condition_axis1, arr_2d, axis=1)
print("Compressed along axis=1:")
print(compressed_axis1)
# Output:
# [[1]
# [3]
# [5]]Using the out Parameter#
For large arrays, reusing memory with out avoids creating new arrays:
# Pre-allocate output array (shape matches compressed_axis0)
out_array = np.empty((2, 2), dtype=int)
# Apply compress with out
np.compress(condition, arr_2d, axis=0, out=out_array)
print("Output using 'out' parameter:")
print(out_array)
# Output:
# [[1 2]
# [5 6]]Common Practices and Best Practices#
When to Use numpy.compress()#
- Axis-Specific Selection: Use
compresswhen you need to select rows/columns (or higher-dimensional axes) while preserving array structure. - Memory Efficiency: Use
outto reuse memory for large arrays. - Alternative to Boolean Indexing: For 1D arrays, boolean indexing (e.g.,
arr[condition]) is simpler, butcompressis better for axis-aware selection in multi-dimensional arrays.
Best Practices#
- Validate
conditionLength: Ensureconditionhas length matching the axis size (ifaxisis set) or the total number of elements (ifaxis=None). - Specify
axisClearly: Avoid unexpected flattening by explicitly settingaxis. - Handle Empty Outputs: If all
conditionvalues areFalse, the output will be an empty array. Check for this to avoid errors. - Use
outfor Large Arrays: Reuse memory withoutto reduce overhead.
Use Cases#
- Data Filtering: Select rows from a dataset where a column value meets a criterion (e.g.,
condition = data[:, 0] > 10for a 2D dataset). - Feature Selection: In machine learning, select features (columns) where a statistical test (e.g., correlation with target) is significant.
- Image Processing: Apply a mask (boolean array) to an image (3D array) to select pixels along a specific axis (e.g., color channels).
- Time Series: Select time steps (rows) where a metric (e.g., sales > threshold) is met.
Limitations and Considerations#
conditionMust Be 1D: If you have a 2D boolean mask, flatten it (e.g.,condition = mask.ravel()) or use boolean indexing.- Axis Validity:
axismust be a valid integer (0 tondim(a)-1). - Performance: For extremely large arrays,
compressmay be slower than boolean indexing. Profile and optimize as needed.
Conclusion#
numpy.compress() is a versatile tool for selecting array elements based on a condition, with support for axis-specific operations. By mastering its syntax, parameters, and best practices, you can efficiently filter data, select features, and manipulate multi-dimensional arrays in numerical computing tasks.
References#
- NumPy Official Documentation:
numpy.compress() - Python Data Science Handbook (Jake VanderPlas) for NumPy array manipulation.
This guide equips you to leverage numpy.compress() for efficient array manipulation. Experiment with examples and integrate it into your data workflows!