Digital combination of numpy series and of horizontal and vertical

  • 2021-11-29 07:24:55
  • OfStack

Catalog 1. Horizontal merging 1.1 concatenate method
1.2 hstack method
1.3 column_stack method
2. Vertical consolidation 2.1 concatenate method
2.2 vstack method
2.3 row_stack method

Create two new arrays for merging


import numpy as np
arr1 = np.array([[1, 2, 3], [4, 5, 6]])
print(arr1)

result:
[[1 2 3]
[4 5 6]]


arr2 = np.array([[7, 8, 9], [10, 11, 12]])
print(arr2)

result:
[[ 7 8 9]
[10 11 12]]

1. Horizontal consolidation

Horizontal merging is simply splicing two arrays with the same number of rows in the row direction. The combination of numpy and DataFrame is not the same. The combination of numpy does not need a common column, but simply splices two arrays into one. There are three methods that can be realized: concatenate, hstack and column_stack

1.1 concatenate method

The concatenate method passes two arrays to be merged as a list to concatenate, and sets the axis parameter to indicate whether to merge in the row or column direction. The parameter axis=1 indicates that the array is merged in the row direction


print(np.concatenate([arr1, arr2], axis=1))

result:
[[ 1 2 3 7 8 9]
[ 4 5 6 10 11 12]]

1.2 hstack method

In hstack method, two arrays to be merged are passed to hstack in the form of tuples to achieve the purpose of horizontal merging of arrays


print(np.hstack((arr1, arr2)))

result:
[[ 1 2 3 7 8 9]
[ 4 5 6 10 11 12]]

1.3 column_stack method

column_stack method and hstack method are basically the same, but also two arrays to be merged are passed to column_stack in the form of tuples to achieve the purpose of array horizontal merging


print(np.column_stack((arr1, arr2)))

result:
[[ 1 2 3 7 8 9]
[ 4 5 6 10 11 12]]

2. Vertical consolidation

Vertical merging is to splice two arrays with equal columns in the column direction, which can be realized by concatenate, vstack and row_stack

2.1 concatenate method

The concatenate method passes two arrays to be merged as a list to concatenate, and sets the axis parameter to indicate whether the merge is in the row or column direction. Parameter axis=0 indicates merging of arrays in column direction


print(np.concatenate([arr1, arr2], axis=0))

result:
[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]
[10 11 12]]

2.2 vstack method

The vstack method is corresponding to the hstack method. As long as two arrays to be merged are passed to vstack in the form of tuples, the vertical merging of arrays can be achieved


print(np.vstack((arr1, arr2)))

result:
[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]
[10 11 12]]

2.3 row_stack method

The method of row_stack is corresponding to the method of column_stack. As long as two arrays to be merged are passed to row_stack in the form of tuples, the vertical merging of arrays can be achieved


print(np.row_stack((arr1, arr2)))

result:
[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]
[10 11 12]]


Related articles: