![]() |
VOOZH | about |
If an array has negative numbers, you change them to 0, while keeping all non-negative numbers the same. For example: Suppose you have this array: A=[−3, 5, −7, 2, 0, −1], after replacing negatives with zero: A′=[0, 5, 0, 2, 0, 0].
This is the most efficient method if you want to update the original array directly. It uses NumPy’s boolean indexing.
Example: In this example, we create a boolean mask for all negative elements and assign them the value 0 directly inside the same array.
Input: [ 1 2 -3 4 -5 -6] Result: [1 2 0 4 0 0]
Explanation:
This method uses NumPy’s universal function (ufunc) to compare each element with 0.
Example: Here we apply np.maximum to take the larger of each element and 0, ensuring negatives are replaced.
Input: [ 1 2 -3 4 -5 -6] Result: [1 2 0 4 0 0]
Explanation:
np.clip clamps all values to lie within a given range. Setting the lower bound to 0 forces negatives up to 0.
Example: In this example, we clip values of the array to the range [0, upper], so anything below 0 becomes 0.
Input: [ 1 2 -3 4 -5 -6] Result: [1 2 0 4 0 0]
Explanation:
np.where lets you select between two values based on a condition.
Example: This code creates a new array: if an element is negative, it becomes 0; otherwise, it keeps its original value.
Input: [ 1 2 -3 4 -5 -6] Result: [1 2 0 4 0 0]
Explanation:
This method wraps a Python function to apply elementwise. It is slower but sometimes useful for readability.
Example: In this program, a lambda function replaces negative elements with 0 and keeps others unchanged.
Input: [ 1 2 -3 4 -5 -6] Result: [1 2 0 4 0 0]
Explanation: