NumPy Joining Array

M.Ramya

 Joining NumPy Arrays

Joining in NumPy means combining the elements of two or more arrays into a single array.

Unlike SQL, where tables are joined based on keys, NumPy joins arrays along specified axes.

To join arrays, we use the concatenate() function. This function takes a sequence of arrays to join and an optional axis argument. If the axis isn’t provided, it defaults to 0.

Program:

Join Two 1-D Arrays

import numpy as np

arr1 = np.array([1, 2, 3])

arr2 = np.array([4, 5, 6])

result = np.concatenate((arr1, arr2))

print(result)

Output:

[1 2 3 4 5 6]

Program:

Join Two 2-D Arrays Along Columns (axis=1)

import numpy as np

arr1 = np.array([[1, 2], [3, 4]])

arr2 = np.array([[5, 6], [7, 8]])

result = np.concatenate((arr1, arr2), axis=1)

print(result)

Output:

[[1 2 5 6]
 [3 4 7 8]]

Joining Arrays Using Stack Functions

Stacking is similar to concatenation, but it joins arrays along a new axis.

Using the stack() function, we can combine arrays along a new dimension. By default, stacking is done along axis 0 unless specified otherwise.

Program:

Stack Two 1-D Arrays Along a New Axis

import numpy as np

arr1 = np.array([1, 2, 3])

arr2 = np.array([4, 5, 6])

result = np.stack((arr1, arr2), axis=1)

print(result)

Output:

[[1 4]
 [2 5]
 [3 6]]

Stacking Arrays Along Different Axes

NumPy provides specific helper functions for stacking along different axes:

1. Stacking Along Rows (hstack)

Stacks arrays horizontally (along columns).

Program:

import numpy as np

arr1 = np.array([1, 2, 3])

arr2 = np.array([4, 5, 6])

result = np.hstack((arr1, arr2))

print(result)

Output:

[1 2 3 4 5 6]

2. Stacking Along Columns (vstack)

Stacks arrays vertically (along rows).

Program:

import numpy as np

arr1 = np.array([1, 2, 3])

arr2 = np.array([4, 5, 6])

result = np.vstack((arr1, arr2))

print(result)

Output:

[[1 2 3]
 [4 5 6]]

3. Stacking Along Depth (dstack)

Stacks arrays along the third axis (depth).

Program:

import numpy as np

arr1 = np.array([1, 2, 3])

arr2 = np.array([4, 5, 6])

result = np.dstack((arr1, arr2))

print(result)

Output:

[[[1 4]
   [2 5]
   [3 6]]]
Tags
Our website uses cookies to enhance your experience. Learn More
Accept !

GocourseAI

close
send