Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

numpy
python
communitycreator

How to reshape a masked array in NumPy

Onyejiaku Theophilus Chidalu

Overview

A masked array in NumPy can be reshaped using the ma.reshape() function of the numpy.ma module. The new array with a new shape will still have the same data as the original array.

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

Syntax

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

ma.reshape(a, new_shape, order='C')
The syntax for the ma.reshape() function

Parameter value

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

  • a: This is the input array and is required.
  • new_shape: This is the desired shape of the output array. It is also a required parameter.
  • order: This determines the order in which the array data should be viewed. It takes any of the following orders: "C", "F", "A", or "K". This is an optional parameter.

Return value

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

Code

# A code to illustrate the ma.reshape() 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)

# reshaping the array
new_array = ma.reshape(my_array, (4,2), order = "F")

# printing the new array
print(new_array)
Implement the reshape() 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. It has the shape of (2, 4). This means that the two arrays have four elements each.
  • Line 9: We print the input array, my_array.
  • Line 12: We use the ma.reshape() function to reshape the input array to an array of the shape, (4, 2). This means that the four arrays have two elements each. The result is assigned to a variable, new_array.
  • Line 15: We print the new array, new_array.

RELATED TAGS

numpy
python
communitycreator

CONTRIBUTOR

Onyejiaku Theophilus Chidalu
RELATED COURSES

View all Courses

Keep Exploring