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:

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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/numpy/fill-masked-values-in-numpy-array-with-specified-number.php