NumPy Array Reshape

The reshape() method in NumPy allows you to change the shape of an array without modifying its data. Reshaping is useful for organizing datasets into different dimensions, such as transforming census data for cities like Coimbatore (Tamil Nadu, India) or Bengaluru (Karnataka, India).

Key Topics

Basic Reshaping

You can reshape a 1D array into a 2D or 3D array by specifying the desired shape. The total number of elements must remain the same.

Example

# Reshaping a 1D array to 2D
import numpy as np

data = np.array([1, 2, 3, 4, 5, 6])
reshaped = data.reshape(2, 3)

print("Original array:", data)
print("Reshaped array:")
print(reshaped)

Output

Original array: [1 2 3 4 5 6]
Reshaped array:
[[1 2 3]
[4 5 6]]

Explanation: The array is reshaped into 2 rows and 3 columns using reshape(2, 3). The total elements remain the same.

Reshaping with Unknown Dimensions

Use -1 as a placeholder for one dimension when the size of that dimension is unknown. NumPy will automatically calculate the correct size for that dimension.

Example

# Reshaping with an unknown dimension
data = np.array([10, 20, 30, 40, 50, 60])
reshaped = data.reshape(3, -1)

print("Original array:", data)
print("Reshaped array:")
print(reshaped)

Output

Original array: [10 20 30 40 50 60]
Reshaped array:
[[10 20]
[30 40]
[50 60]]

Explanation: The -1 automatically determines the number of columns based on the total elements and the specified number of rows.

Flattening an Array

Flattening converts a multi-dimensional array into a 1D array, which is helpful for certain analyses, such as summarizing sales data for cities like Thanjavur (Tamil Nadu, India).

Example

# Flattening a 2D array
data = np.array([[100, 200], [300, 400]])
flattened = data.flatten()

print("Original array:")
print(data)
print("Flattened array:", flattened)

Output

Original array:
[[100 200]
[300 400]]
Flattened array: [100 200 300 400]

Explanation: The flatten() method converts a 2D array into a 1D array, preserving the order of elements.

Key Takeaways

  • Reshaping Arrays: Use reshape() to reorganize arrays into different dimensions.
  • Unknown Dimensions: Specify -1 for one dimension to let NumPy calculate its size automatically.
  • Flattening: Use flatten() to convert multi-dimensional arrays into 1D arrays.
  • Real-World Applications: Reshape datasets for cities like Coimbatore, Bengaluru, and Thanjavur to suit analytical needs.