Joining or concatenating arrays means combining two or more NumPy arrays into a single array. NumPy provides several functions to do this efficiently.
np.concatenate()
— Joins arrays along an existing axis.np.vstack()
— Stacks arrays vertically (row wise).np.hstack()
— Stacks arrays horizontally (column wise).np.stack()
— Joins arrays along a new axis.joined_array = np.concatenate((arr1, arr2, ...), axis=axis_value)
axis
specifies the axis along which the arrays will be joined. The arrays must have compatible shapes.
axis
.axis=0
concatenates end to end.vstack()
and hstack()
are convenient shortcuts for common concatenations.import numpy as np
# Example 1: Concatenate 1D arrays
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
c = np.concatenate((a, b))
print("Concatenate 1D arrays:")
print(c) # Output: [1 2 3 4 5 6]
# Example 2: Concatenate 2D arrays along rows (axis=0)
a2 = np.array([[1, 2], [3, 4]])
b2 = np.array([[5, 6]])
c2 = np.concatenate((a2, b2), axis=0)
print("\nConcatenate 2D arrays along rows (axis=0):")
print(c2)
# Output:
# [[1 2]
# [3 4]
# [5 6]]
# Example 3: Concatenate 2D arrays along columns (axis=1)
d2 = np.array([[7], [8]])
c3 = np.concatenate((a2, d2), axis=1)
print("\nConcatenate 2D arrays along columns (axis=1):")
print(c3)
# Output:
# [[1 2 7]
# [3 4 8]]
# Example 4: Vertical stack (vstack)
vstacked = np.vstack((a2, b2))
print("\nVertical stack (vstack):")
print(vstacked)
# Example 5: Horizontal stack (hstack)
hstacked = np.hstack((a2, d2))
print("\nHorizontal stack (hstack):")
print(hstacked)
# Example 6: Stack along a new axis (axis=0)
stacked = np.stack((a, b), axis=0)
print("\nStack along a new axis (axis=0):")
print(stacked)
# Output:
# [[1 2 3]
# [4 5 6]]
ValueError: all the input arrays must have same shape
— arrays have incompatible shapes.np.concatenate()
for flexible array joining along existing axes.vstack()
and hstack()
are convenient for vertical and horizontal joining.stack()
adds a new dimension and is useful for higher-dimensional arrays.Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!