Instagram
youtube
Facebook
Twitter

Replace Even Numbers in NumPy Array with -1

A Replace Even Numbers in NumPy Array with -1?
Code Explanation:
● Library Import:
numpy is imported as np to handle array operations.
● Array Creation: A 1D NumPy array arr is created with a mix of even and odd numbers.
● Condition Check: arr % 2 == 0 creates a boolean mask for all even numbers in the array.
● Element Replacement: arr[...] = -1 replaces all elements where the condition is True (even numbers) with -1.
● In-place Modification: The changes are made directly to the original array.
● Display Output: print(arr) shows the modified array: [ 1 -1 3 -1 5 -1].

 

Program:

import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6])

arr[arr % 2 == 0] = -1

print(arr)