NumPy Array Shape

The shape of a NumPy array refers to the number of elements in each dimension. Understanding the shape is crucial when working with multi-dimensional data, such as population statistics or geographic data from cities like Madurai (Tamil Nadu, India) and Varanasi (Uttar Pradesh, India).

Key Topics

Checking the Shape of an Array

Use the shape attribute to find the dimensions of a NumPy array. This is particularly useful when handling multi-dimensional arrays for tabular data.

Example

# Checking the shape of arrays
import numpy as np

# 1D array
array_1d = np.array([1, 2, 3, 4])
print("Shape of 1D array:", array_1d.shape)

# 2D array
array_2d = np.array([[1, 2], [3, 4], [5, 6]])
print("Shape of 2D array:", array_2d.shape)

Output

Shape of 1D array: (4,)
Shape of 2D array: (3, 2)

Explanation: The shape attribute returns a tuple representing the dimensions of the array. For example, (3, 2) indicates 3 rows and 2 columns in a 2D array.

Modifying the Shape of an Array

You can modify the shape of an array using the reshape() method. This is helpful when you need to reorganize data, such as rainfall measurements in Kanchipuram (Tamil Nadu, India).

Example

# Reshaping arrays
rainfall = np.array([100, 200, 150, 175, 120, 300])
reshaped = rainfall.reshape(2, 3)

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

Output

Original array: [100 200 150 175 120 300]
Reshaped array:
[[100 200 150]
[175 120 300]]

Explanation: The reshape() method rearranges the elements into a 2x3 array. The total number of elements in the reshaped array must match the original array.

Key Takeaways

  • Shape Attribute: Use shape to find the dimensions of an array.
  • Reshape Method: Use reshape() to modify the dimensions of an array while preserving its elements.
  • Data Compatibility: Ensure the reshaped array's total elements match the original array.
  • Real-World Applications: Analyze datasets from cities like Madurai, Varanasi, and Kanchipuram using array shapes.