SoFunction
Updated on 2025-03-02

How to use vstack and hstack in Numpy

1. Overview

In Numpy, the most desired data is arrays and matrices. Here are two methods of splicing arrays: vstack() and hstack();

The usage of these two methods is roughly the same, but there are some differences in functions.

2. vstack()

2.1 Syntax

(tup) 

Vertically stack arrays (row method).

2.2 Parameters

tup —— The sequence of ndarrays

  • The array must have the same shape except for the first axis (row).
  • One-dimensional arrays must have the same length.

return:

  • Return the stacked array
  • The final array formed by stacking the given array will be at least two-dimensional

2.3 Example

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2019/1/22 9:33
# @Author  : Arrow and Bullet
# @FileName: vstack_hstack.py
# @Software: PyCharm
# @Blog    :/qq_41800366
from numpy import *  #Introduce numpy
A = array([1, 2, 3])
B = array([4, 5, 6])
C = vstack((A, B))
print(C)  # Results [[1 2 3] [4 5 6]]print(type(C))  # Result <class ''>
A = array([[1], [2], [3]])
B = array([[4], [5]])
C = vstack((A, B))
print(C)  # result [[1][2][3][4][5]]

3. hstack()

3.1 Syntax

(tup) 

Stack arrays (column formulas) in order.

3.2 Parameters

tup —— The sequence of ndarrays

  • All arrays except the second axis (column) must have the same shape.

return:

  • Arrays formed by stacking a given array.

3.3 Example

from numpy import *  #Introduce numpy
A = array([1, 2, 3])
B = array([4, 5, 6])
C = hstack((A, B))
print(C)  # Results [1 2 3 4 5 6]print(type(C))  # Result <class ''>
A = array([[1], [2], [3]])
B = array([[4], [5], [6]])
C = hstack((A, B))
print(C)  # result [[1 4][2 5][3 6]]

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.