Take two NumPy arrays having two dimensions. Concatenate the arrays on axis 1

import numpy as np

ar1 = np.array([[1, 2, 3], [4, 5, 6]])
ar2 = np.array([[10, 20, 30], [40, 50, 60]])
c = np.concatenate((ar1, ar2), axis=1)
print(c)
Output : 
[[ 1  2  3 10 20 30]
 [ 4  5  6 40 50 60]]

Certainly! The provided Python code uses the NumPy library to concatenate two arrays along the horizontal axis (axis=1). Here’s how it works:

Explanation

  1. Import NumPy Library:
   import numpy as np
  • This line imports the NumPy library, which is a powerful library for numerical computing in Python.
  1. Create NumPy Arrays:
   ar1 = np.array([[1, 2, 3], [4, 5, 6]])
   ar2 = np.array([[10, 20, 30], [40, 50, 60]])
  • These lines create two NumPy arrays, ar1 and ar2, each containing two rows and three columns of integer values.
  1. Concatenate Arrays Horizontally:
   c = np.concatenate((ar1, ar2), axis=1)
  • np.concatenate is used to concatenate the arrays ar1 and ar2 along the horizontal axis (axis=1).
  • The result is stored in the variable c.
  1. Print the Result:
   print(c)
  • This line prints the concatenated array c, which contains the elements from both ar1 and ar2 arranged horizontally.

Example

Let’s go through the example provided:

  • Input Arrays:
  ar1 = np.array([[1, 2, 3], [4, 5, 6]])
  ar2 = np.array([[10, 20, 30], [40, 50, 60]])
  • Concatenation:
  • np.concatenate((ar1, ar2), axis=1) concatenates the arrays ar1 and ar2 along the horizontal axis (columns).
  • The resulting array c will have the shape (2, 6), containing the elements from both ar1 and ar2 arranged horizontally.
  • Result:
  [[ 1  2  3 10 20 30]
   [ 4  5  6 40 50 60]]

Summary

This code demonstrates how to concatenate two NumPy arrays along the horizontal axis (columns). It uses the np.concatenate function with axis=1 to achieve this, resulting in a new array where the elements of both input arrays are arranged side by side horizontally.

Leave a Reply

Your email address will not be published. Required fields are marked *