w3resource

Fill Masked values in NumPy array with specified number


2. Masked Array Fill

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.

For more Practice: Solve these Related Problems:

  • Write a Numpy program to create a masked array and then fill the masked values with zero.
  • Write a Numpy program to fill the masked values of a 2D masked array with the median of the unmasked elements.
  • Write a Numpy program to replace masked elements with a user-defined constant in a masked array derived from a random dataset.
  • Write a Numpy program to fill a masked array's masked values with the maximum value from its unmasked data.

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Creating a Masked array in NumPy.
Next: Compute Mean of a Masked array ignoring Masked values in NumPy.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.