Stack arrays in sequence vertically (row wise) in Numpy

NumpyServer Side ProgrammingProgramming

To stack arrays in sequence vertically (row wise), use the ma.row_stack() method in Python Numpy. This is equivalent to concatenation along the first axis after 1-D arrays of shape (N,) have been reshaped to (1,N). Rebuilds arrays divided by vsplit. Returns the array formed by stacking the given arrays, will be at least 2-D.

This function makes most sense for arrays with up to 3 dimensions. For instance, for pixel-data with a height (first axis), width (second axis), and r/g/b channels (third axis). The functions concatenate, stack and block provide more general stacking and concatenation operations. It is applied to both the _data and the _mask, if any.

The parameters are the arrays that must have the same shape along all but the first axis. 1-D arrays must have the same length.

Steps

At first, import the required library −

import numpy as np
import numpy.ma as ma

Create a new array using the array() method −

arr = np.array([[200], [300], [400], [500]])
print("Array...\n", arr)

Type of array −

print("\nArray type...\n", arr.dtype)

Get the dimensions of the Array −

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

To stack arrays in sequence vertically (row wise), use the ma.row_stack() method −

resArr = np.ma.row_stack (arr)

Resultant Array −

print("\nResult...\n", resArr)

Example

# Python ma.MaskedArray - Stack arrays in sequence vertically (row wise)

import numpy as np
import numpy.ma as ma

# Create a new array using the array() method
arr = np.array([[200], [300], [400], [500]])
print("Array...\n", arr)

# Type of array
print("\nArray type...\n", arr.dtype)

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

# To stack arrays in sequence vertically (row wise), use the ma.row_stack() method in Python Numpy
resArr = np.ma.row_stack (arr)

# Resultant Array
print("\nResult...\n", resArr)

Output

Array...
[[200]
[300]
[400]
[500]]

Array type...
int64

Array Dimensions...
2

Result...
[[200]
[300]
[400]
[500]]
raja
Updated on 03-Feb-2022 12:13:18

Advertisements