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
- Import NumPy Library:
import numpy as np
- This line imports the NumPy library, which is a powerful library for numerical computing in Python.
- 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
andar2
, each containing two rows and three columns of integer values.
- Concatenate Arrays Horizontally:
c = np.concatenate((ar1, ar2), axis=1)
np.concatenate
is used to concatenate the arraysar1
andar2
along the horizontal axis (axis=1).- The result is stored in the variable
c
.
- Print the Result:
print(c)
- This line prints the concatenated array
c
, which contains the elements from bothar1
andar2
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 arraysar1
andar2
along the horizontal axis (columns).- The resulting array
c
will have the shape (2, 6), containing the elements from bothar1
andar2
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.