Combine two arrays into one in Python



How to connect NumPy clusters(array) in Python?

You can utilize the numpy.concatenate() capability to concat, union, or join a grouping of two or various clusters into a solitary NumPy exhibit. Link alludes to placing the items in at least two exhibits in a solitary cluster. In Python NumPy, we can join clusters by tomahawks (vertical or level), though in SQL we join tables in view of keys.

You can pass a grouping of clusters that you need to join to the link() capability, alongside the hub. On the off chance that the hub isn't expressly passed, it is taken as 0. In this article, we will clarify how for link NumPy clusters (ndarray) with models by utilizing capabilities like concatenate(), stack(), hstack(), vstack(), dstack().


Note: that in Python NumPy, ndarray is a multi-layered, homogeneous exhibit of fixed-size things of a similar sort. You can make a ndarray object by utilizing NumPy.array().


1. using concatenate()

To combine the contents of two or more arrays into one array, use numpy.concatenate(). This function concatenates NumPy arrays with a number of arguments and returns a Numpy array called ndarray. Keep in mind that this method also accepts an additional argument, axis, which defaults to 0 if left unspecified.

Python Code:


import numpy as np

#Create NumPy arrays
arr = np.array([4, 7, 12])
arr1 = np.array([5, 9, 15])

# Use concatenate() to join two arrays
con = np.concatenate((arr, arr1))
print(con)

Output:



2. using numpy.stack()

To join a series of arrays along a new axis, use numpy.stack(). The axis and a list of arrays you want to join are passed to the numpy.stack() function. The axis is assumed to be zero if it is not explicitly passed.

Python Code:


import numpy as np

#Create NumPy arrays
arr = np.array([4, 7, 12])
arr1 = np.array([5, 9, 15])

con = np.stack((arr, arr1), axis=1)
print(con)

Output:



3. Use NumPy.hstack() Function

This function does not work with the axis. It extends the first array by the second array

Horizontally.

As it extends horizontally, both the arrays should have the same number of rows else

Value Error will be returned.

Example:

Python Code:


import numpy as np

#Create NumPy arrays
arr = np.array([4, 7, 12])
arr1 = np.array([5, 9, 15])

con = np.hstack((arr, arr1))
print(con)

Output:


4. NumPy.vstack() Function

This function does not work with axis. It extends the first array by the second array

Vertically.


Python Code:


import numpy as np

#Create NumPy arrays
arr = np.array([4, 7, 12])
arr1 = np.array([5, 9, 15])

con = np.vstack((arr, arr1))
print(con)

Output:


5. Use numpy.dstack() Function

The dstack() is used to stack arrays in sequence depth-wise (along the third axis).




I hope you like this article.

Thanks

Amandeep Singh

626 views0 comments