Stack 1-D arrays as columns into a 2-D array in Numpy

NumpyServer Side ProgrammingProgramming

To stack 1-D arrays as columns into a 2-D array, use the ma.column_stack() method in Python Numpy. Take a sequence of 1-D arrays and stack them as columns to make a single 2-D array. 2-D arrays are stacked as-is, just like with hstack. 1-D arrays are turned into 2-D columns first. The parameters are the Arrays to stack. All of them must have the same first dimension.

Returns the array formed by stacking the given arrays. It is applied to both the _data and the _mask, if any.

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 1-D arrays as columns into a 2-D array, use the ma.column_stack() method in Python Numpy:

resArr = np.ma.column_stack (arr)

Resultant Array −

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

Example

# Python ma.MaskedArray - Stack 1-D arrays as columns into a 2-D array

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 1-D arrays as columns into a 2-D array, use the ma.column_stack() method in Python Numpy
resArr = np.ma.column_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:15:25

Advertisements