NumPy Array Join

Joining arrays in NumPy combines two or more arrays into one. This is particularly useful when merging datasets, such as combining population statistics from cities like Chennai (Tamil Nadu, India) and Kolkata (West Bengal, India).

Key Topics

Joining 1D Arrays

1D arrays can be joined using the concatenate() function, which combines elements from both arrays.

Example

# Joining 1D arrays
import numpy as np

array1 = np.array([1, 2, 3])
array2 = np.array([4, 5, 6])
joined = np.concatenate((array1, array2))

print("Joined array:", joined)

Output

Joined array: [1 2 3 4 5 6]

Explanation: The concatenate() function merges array1 and array2 into a single 1D array.

Joining 2D Arrays

2D arrays can be joined along rows or columns using the concatenate() function with the axis parameter.

Example

# Joining 2D arrays
array1 = np.array([[1, 2], [3, 4]])
array2 = np.array([[5, 6], [7, 8]])

# Join along rows
joined_rows = np.concatenate((array1, array2), axis=0)

# Join along columns
joined_columns = np.concatenate((array1, array2), axis=1)

print("Joined along rows:")
print(joined_rows)
print("Joined along columns:")
print(joined_columns)

Output

Joined along rows:
[[1 2]
[3 4]
[5 6]
[7 8]]

Joined along columns:
[[1 2 5 6]
[3 4 7 8]]

Explanation: Setting axis=0 joins along rows, while axis=1 joins along columns. Ensure the arrays have compatible shapes for the specified axis.

Joining Using Stack Methods

The stack() methods (vstack(), hstack(), and dstack()) provide alternative ways to join arrays. These are helpful when working with multi-dimensional data.

Example

# Joining arrays using stack methods
array1 = np.array([1, 2])
array2 = np.array([3, 4])

# Vertical stack
v_stacked = np.vstack((array1, array2))

# Horizontal stack
h_stacked = np.hstack((array1, array2))

print("Vertically stacked:")
print(v_stacked)
print("Horizontally stacked:")
print(h_stacked)

Output

Vertically stacked:
[[1 2]
[3 4]]

Horizontally stacked:
[1 2 3 4]

Explanation: vstack() stacks arrays vertically (row-wise), and hstack() stacks arrays horizontally (column-wise).

Key Takeaways

  • 1D Joins: Use concatenate() to merge 1D arrays.
  • 2D Joins: Specify axis to join along rows or columns.
  • Stack Methods: Use vstack(), hstack(), or dstack() for flexible array joining.
  • Real-World Applications: Combine datasets for cities like Chennai and Kolkata for comprehensive analysis.