Introduction
Joining arrays in NumPy is a common operation that allows you to combine multiple arrays into a single array. This can be done in several ways, such as concatenation, stacking, and using specific joining functions. In this chapter, you will learn different ways to join arrays in NumPy.
Importing NumPy
First, import NumPy in your script or notebook:
import numpy as np
Concatenation
The concatenate
function in NumPy joins a sequence of arrays along an existing axis.
Example: Concatenating 1D Arrays
# Creating 1D arrays
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
# Concatenating arrays
result = np.concatenate((arr1, arr2))
print(result)
Output:
[1 2 3 4 5 6]
Example: Concatenating 2D Arrays
# Creating 2D arrays
arr1 = np.array([[1, 2], [3, 4]])
arr2 = np.array([[5, 6], [7, 8]])
# Concatenating along axis 0 (rows)
result = np.concatenate((arr1, arr2), axis=0)
print(result)
Output:
[[1 2]
[3 4]
[5 6]
[7 8]]
# Concatenating along axis 1 (columns)
result = np.concatenate((arr1, arr2), axis=1)
print(result)
Output:
[[1 2 5 6]
[3 4 7 8]]
Stacking
NumPy provides functions like vstack
, hstack
, and dstack
for stacking arrays vertically, horizontally, and depth-wise, respectively.
Example: Vertical Stacking
# Creating 1D arrays
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
# Vertical stacking
result = np.vstack((arr1, arr2))
print(result)
Output:
[[1 2 3]
[4 5 6]]
Example: Horizontal Stacking
# Creating 2D arrays
arr1 = np.array([[1, 2], [3, 4]])
arr2 = np.array([[5, 6], [7, 8]])
# Horizontal stacking
result = np.hstack((arr1, arr2))
print(result)
Output:
[[1 2 5 6]
[3 4 7 8]]
Example: Depth-Wise Stacking
# Creating 2D arrays
arr1 = np.array([[1, 2], [3, 4]])
arr2 = np.array([[5, 6], [7, 8]])
# Depth-wise stacking
result = np.dstack((arr1, arr2))
print(result)
Output:
[[[1 5]
[2 6]]
[[3 7]
[4 8]]]
Using stack Function
The stack
function joins arrays along a new axis.
Example: Stacking Along a New Axis
# Creating 1D arrays
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
# Stacking along a new axis
result = np.stack((arr1, arr2), axis=1)
print(result)
Output:
[[1 4]
[2 5]
[3 6]]
Using column_stack and row_stack
column_stack
and row_stack
functions stack 1D arrays as columns or rows, respectively, to make 2D arrays.
Example: Column Stacking
# Creating 1D arrays
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
# Column stacking
result = np.column_stack((arr1, arr2))
print(result)
Output:
[[1 4]
[2 5]
[3 6]]
Example: Row Stacking
# Creating 1D arrays
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
# Row stacking
result = np.row_stack((arr1, arr2))
print(result)
Output:
[[1 2 3]
[4 5 6]]
Conclusion
Joining arrays in NumPy can be done using various functions like concatenate
, stack
, vstack
, hstack
, dstack
, column_stack
, and row_stack
. These functions allow you to combine arrays in different ways, making it easier to manipulate and analyze your data efficiently.