Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

numpy
python
communitycreator

How to resize a masked array in NumPy

Onyejiaku Theophilus Chidalu

Overview

The size of an array in NumPy describes the number of elements in the given array. For example, an array whose size is (4, 2) means that it contains eight elements.

A masked array is an array that has any or all of its elements hidden or masked with a --.

We use the ma.resize() function of the numpy.ma module to resize a masked array to a new dimension.

Syntax

The ma.resize() function takes the following syntax:

ma.resize(a, new_shape)
The syntax for the ma.resize() function

Parameter value

The ma.resize() function takes the following parameter values:

  • a: This is the input array and is a required parameter.
  • new_shape: This is the desired size of the output array. It is also a required parameter.

Return value

The ma.resize() function returns an array of the same data as the input array but with a different size.

Code

# A code to illustrate the ma.resize() function in NumPY
# importing the numpy.ma module
import numpy.ma as ma

# creating a masked array
my_array = ma.array([[1, 2, 3, 4] ,[5, 6, 7, 8]], mask=[1,0,1,0,1,0,1,0])

# printing the input array
print(my_array)

# resizing the array
new_array = ma.resize(my_array, (5,10))

# printing the new array
print(new_array)
Implement the ma.resize() function

Explanation

  • Line 3: We import the numpy.ma module.
  • Line 6: We use the ma.array() function to create a masked 2D array my_array whose shape is (2, 4). This means that the two arrays have four elements each.
  • Line 9: We print the input array, my_array.
  • Line 12: We resize the input array using the ma.resize() function into an array whose size is (5, 10). This means it is an array containing 50 elements. We assign the result to a variable, new_array.
  • Line 15: We print new_array.

RELATED TAGS

numpy
python
communitycreator

CONTRIBUTOR

Onyejiaku Theophilus Chidalu
RELATED COURSES

View all Courses

Keep Exploring