Return a new array with the same shape and type as a given array in Numpy

NumpyServer Side ProgrammingProgramming

To return a new array with the same shape and type as a given array, use the ma.empty_like() method in Python Numpy. It returns and array of uninitialized (arbitrary) data with the same shape and type as prototype.

The order parameter overrides the memory layout of the result. 'C' means C-order, 'F' means Forder, 'A' means 'F' if prototype is Fortran contiguous, 'C' otherwise. 'K' means match the layout of prototype as closely as possible.

Steps

At first, import the required library −

import numpy as np
import numpy.ma as ma

Create a new array using the numpy.array() method in Python Numpy −

arr = np.array([[77, 51, 92], [56, 31, 69], [73, 88, 51], [62, 45, 67]])

Displaying our array −

print("Array...\n",arr)

To return a new array with the same shape and type as a given array, use the ma.empty_like() method in Python Numpy. The parameter is the prototype i.e. the shape and data-type of prototype define these same attributes of the returned array −

arr = ma.empty_like(arr)

Displaying our array −

print("\nNew Array...\n",arr)

Get the dimensions of the Array −

print("\nArray Dimensions...\n",arr.ndim)

Get the shape of the Array −

print("\nOur Array Shape...\n",arr.shape)

Get the number of elements of the Array −

print("\nElements in the Array...\n",arr.size)

Example

# Python ma.MaskedArray - Return a new array with the same shape and type as a given array

import numpy as np
import numpy.ma as ma

# Create a new array using the numpy.array() method in Python Numpy
arr = np.array([[77, 51, 92], [56, 31, 69], [73, 88, 51], [62, 45, 67]])

# Displaying our array
print("Array...\n",arr)

# To return a new array with the same shape and type as a given array, use the ma.empty_like() method in Python Numpy
# The parameter is the prototype i.e. the shape and data-type of prototype define these same attributes of the returned array
arr = ma.empty_like(arr)

# Displaying our array
print("\nNew Array...\n",arr)

# Get the dimensions of the Array
print("\nArray Dimensions...\n",arr.ndim)

# Get the shape of the Array
print("\nOur Array Shape...\n",arr.shape)

# Get the number of elements of the Array
print("\nElements in the Array...\n",arr.size)

Output

Array...
[[77 51 92]
[56 31 69]
[73 88 51]
[62 45 67]]

New Array...
[[ 0 0 0]
[ 0 140657801869488 140657802018864]
[140657801869552 140657801869616 140657801869680]
[140657801997616 140657801869744 140657801997680]]

Array Dimensions...
2

Our Array Shape...
(4, 3)

Elements in the Array...
12
raja
Updated on 03-Feb-2022 11:10:35

Advertisements