w3resource

NumPy: Concatenate two 2-dimensional arrays

NumPy: Array Object Exercise-58 with Solution

Write a NumPy program to concatenate two 2-dimensional arrays.
Sample arrays: ([[0, 1, 3], [5, 7, 9]], [[0, 2, 4], [6, 8, 10]]

Pictorial Presentation:

Python NumPy: Concatenate two 2-dimensional arrays

Sample Solution:

Python Code:

# Importing the NumPy library with an alias 'np'
import numpy as np

# Creating two NumPy arrays 'a' and 'b'
a = np.array([[0, 1, 3], [5, 7, 9]])
b = np.array([[0, 2, 4], [6, 8, 10]])

# Concatenating arrays 'a' and 'b' along the second axis (horizontally) using np.concatenate
c = np.concatenate((a, b), 1)

# Printing the concatenated array 'c'
print(c) 

Sample Output:

[[ 0  1  3  0  2  4]                                                   
 [ 5  7  9  6  8 10]] 

Explanation:

In the above code –

‘a = np.array([[0, 1, 3], [5, 7, 9]])’ creates a 2D array a with shape (2, 3).

‘b = np.array([[0, 2, 4], [6, 8, 10]])’ creates another 2D array b with shape (2, 3).

c = np.concatenate((a, b), 1): The np.concatenate() function is used to join the two arrays ‘a’ and ‘b’ along the second axis (axis=1). The resulting array ‘c’ has the shape (2, 6), with the columns of ‘b’ appended to the columns of ‘a’.

Python-Numpy Code Editor:

Previous: Write a NumPy program to remove single-dimensional entries from a specified shape.
Next: Write a NumPy program to convert 1-D arrays as columns into a 2-D array.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/numpy/python-numpy-exercise-58.php