w3resource

Convert Masked NumPy array to Regular array with NaN


NumPy: Masked Arrays Exercise-12 with Solution


Write a NumPy program to create a masked array and convert it back to a regular NumPy array, replacing the masked values with NaN.

Sample Solution:

Python Code:

import numpy as np
import numpy.ma as ma

# Create a 2D NumPy array of shape (4, 4) with random integers
array_2d = np.random.randint(0, 100, size=(4, 4)).astype(float)

# Define the condition to mask elements greater than 50
condition = array_2d > 50

# Create a masked array from the 2D array using the condition
masked_array = ma.masked_array(array_2d, mask=condition)

# Convert the masked array back to a regular NumPy array, replacing masked values with NaN
regular_array_with_nan = masked_array.filled(np.nan)

# Print the original array, the masked array, and the converted array
print('Original 2D array:\n', array_2d)
print('Masked array (elements > 50 are masked):\n', masked_array)
print('Converted array with NaN for masked values:\n', regular_array_with_nan)

Output:

Original 2D array:
 [[43. 64.  0. 39.]
 [74. 96. 79. 66.]
 [14. 14.  1. 85.]
 [17. 65. 98. 76.]]
Masked array (elements > 50 are masked):
 [[43.0 -- 0.0 39.0]
 [-- -- -- --]
 [14.0 14.0 1.0 --]
 [17.0 -- -- --]]
Converted array with NaN for masked values:
 [[43. nan  0. 39.]
 [nan nan nan nan]
 [14. 14.  1. nan]
 [17. nan nan nan]]

Explanation:

  • Import Libraries:
    • Imported numpy as "np" for array creation and manipulation.
    • Imported numpy.ma as "ma" for creating and working with masked arrays.
  • Create 2D NumPy Array:
    • Create a 2D NumPy array named 'array_2d' with random integers ranging from 0 to 99 and a shape of (4, 4).
    • Converted the array to float type using .astype(float) to ensure compatibility with 'np.nan'.
  • Define Condition:
    • Define a condition to mask elements in the array that are greater than 50.
  • Create Masked Array:
    • Create a masked array from the 2D array using ma.masked_array, applying the condition as the mask. Elements greater than 50 are masked.
  • Convert Masked Array to Regular Array with NaN:
    • Converted the masked array back to a regular NumPy array using the filled method, replacing the masked values with NaN.
  • Print the original 2D array, the masked array, and the converted array with NaN for masked values.

Python-Numpy Code Editor: