What is NumPy Column Stacking?

Numpy column_stack() function is used to stack 1-Dimensional array column-wise. And 2-Dimensional array is stacked similar to horizontal stacking(hstack()).

Syntax for Numpy column_stack()

np.column_stack(tup)

You pass Numpy arrays in the form of list or tuple to column_stack() function.

Python program to column stack 1-Dimensional Numpy Array

import numpy as np
 
x = np.array([1, 2, 3, 4])
y = np.array([5, 6, 7, 8])
print('First array x:\n', x)
print('Second array y:\n', y)
print('Column stacked array:\n', np.column_stack((x,y)))

Output of the above program

First array x:
 [1 2 3 4]
Second array y:
 [5 6 7 8]
Column stacked array:
 [[1 5]
 [2 6]
 [3 7]
 [4 8]]

Python program to column stack 2-Dimensional Numpy Array

import numpy as np

x = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
y = np.array([[11, 12, 13, 14, 15], [16, 17, 18, 19, 20]])
print('First array x:\n', x)
print('Second array y:\n', y)
print('Column stacked array:\n', np.column_stack((x,y)))

Output of the above program

First array x:
 [[ 1  2  3  4  5]
 [ 6  7  8  9 10]]
Second array y:
 [[11 12 13 14 15]
 [16 17 18 19 20]]
Column stacked array:
 [[ 1  2  3  4  5 11 12 13 14 15]
 [ 6  7  8  9 10 16 17 18 19 20]]

Recommended Posts