w3resource

Fill Masked values in NumPy array with specified number


NumPy: Masked Arrays Exercise-2 with Solution


Write a NumPy program that creates a masked array and fills the masked values with a specified number.

Sample Solution:

Python Code:

import numpy as np  # Import NumPy library

# Create a regular NumPy array
data = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

# Create a mask to specify which values to mask
mask = np.array([False, True, False, True, False, True, False, True, False, True])

# Create a masked array using the regular array and the mask
masked_array = np.ma.masked_array(data, mask=mask)

# Fill the masked values with a specified number (e.g., -1)
filled_array = np.ma.filled(masked_array, fill_value=-1)

# Print the original masked array and the filled array
print("Original Masked Array:")
print(masked_array)

print("\nFilled Array:")
print(filled_array)

Output:

Original Masked Array:
[1 -- 3 -- 5 -- 7 -- 9 --]

Filled Array:
[ 1 -1  3 -1  5 -1  7 -1  9 -1]

Explanation:

  • Import NumPy Library:
    • Import the NumPy library to handle array operations.
  • Create a Regular Array:
    • Define a NumPy array with integer values from 1 to 10.
  • Define the Mask:
    • Create a Boolean mask array where True indicates the values to be masked.
  • Create the Masked Array:
    • Use “np.ma.masked_array()” to create a masked array from the regular array and the mask.
  • Fill Masked Values:
    • Use "np.ma.filled()" to replace masked values in the masked array with a specified number (e.g., -1).
  • Finally print the original masked array and the filled array to verify the operation.

Python-Numpy Code Editor: