ADVERTISEMENT
ADVERTISEMENT

How to Join Two NumPy Arrays?

NumPy, a powerful Python toolkit for numerical calculation, has many ways to combine or connect arrays. Numpy.concatenate,.hstack, and.vstack can do this operation. Numpy.concatenate connects arrays along an axis. The numpy.hstack and numpy.vstack functions stack arrays horizontally and vertically, respectively. Many circumstances require join procedures to combine data from diverse sources or build larger datasets from smaller ones.

Different Ways to Join NumPy Arrays

1. np.concatenate. This function is used to join two or more arrays along an existing axis. In simpler terms, think of it as gluing together arrays in a row or column direction. For example, if you have two arrays:

import numpy as np

a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
c = np.concatenate((a, b))

print(c)
# Output: array([1, 2, 3, 4, 5, 6])

When you are dealing with multi-dimensional arrays, you can specify the axis.

Here's an example with 2D arrays:

a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6]])
c = np.concatenate((a, b), axis=0)

print(c)
# Output: 
# [[1 2]
#  [3 4]
#  [5 6]]

2. np.vstack(vertical Stack): This function stacks arrays vertically (row-wise). It's similar to concatenate, but designed specifically for vertical stacking.

a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
c = np.vstack((a, b))

print(c)

# Output: 
# [[1, 2, 3]
#  [4, 5, 6]]

3. np.hstack(Horizontal Stack): This function stacks arrays horizontally (column-wise).

a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
c = np.hstack((a, b))

print(c)
# Output: [1, 2, 3, 4, 5, 6]

4. np.append: This function adds values to the end of an array.

a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
c = np.append(a, b)

print(c)

# Output: array([1, 2, 3, 4, 5, 6])

 


ADVERTISEMENT

ADVERTISEMENT