NumPy Shape and Array Dimensions in Python

While I was working on a data analysis project, I needed to manipulate large datasets efficiently. The issue is, understanding the structure of your NumPy arrays is crucial for almost any data operation.

In this article, I’ll cover several simple ways to use and understand the NumPy shape attribute (one using basic arrays and one using real-world examples).

So let’s dive in!

NumPy Shape

Before I learn to use NumPy shape in Python, let me quickly explain what it is and why it’s so important.

The shape attribute helps us understand the dimensions and size of NumPy arrays. Think of it as your “array structure detector.”

Let me explain with a practical example.

Let’s say you’re analyzing sales data for different store locations across the United States. You have:

  • Sales figures for the 50 states
  • Across 12 months
  • For 5 different product categories

This three-dimensional data structure would have a shape of (50, 12, 5). The shape attribute makes it easy to verify your data has the structure you expect before you perform operations on it.

Read Python NumPy Not Found: Fix Import Error

Basic Usage of NumPy Shape

Let’s look at how we can use the shape attribute in Python NumPy. Here’s a simple example:

import numpy as np

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

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

# Create a 3D array
array_3d = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
print("3D array shape:", array_3d.shape)

This would output:

1D array shape: (5,)
2D array shape: (2, 3)
3D array shape: (2, 2, 2)

I executed the above example code and added the screenshot below.

.shape[0] python

The shape attribute returns a tuple showing the size of each dimension. For a 1D array, it’s simply the number of elements. For a 2D array, it’s (rows, columns). For higher dimensions, it follows the same pattern.

Check out Create a Matrix in Python

Use Shape with Real-World Data

Let’s use a more practical example. Imagine we’re analyzing temperature data for major US cities:

import numpy as np

# Daily temperatures (°F) for 3 cities over 5 days
temperature_data = np.array([
    # New York, Chicago, Los Angeles
    [45, 32, 68],  # Monday
    [47, 34, 70],  # Tuesday
    [49, 35, 71],  # Wednesday
    [51, 36, 73],  # Thursday
    [53, 37, 75]   # Friday
])

print("Temperature data shape:", temperature_data.shape)
print("Number of days:", temperature_data.shape[0])
print("Number of cities:", temperature_data.shape[1])

The output would be:

Temperature data shape: (5, 3)
Number of days: 5
Number of cities: 3

I executed the above example code and added the screenshot below.

numpy shape

This shows we have a 2D array with 5 rows (days) and 3 columns (cities).

Read Random Number Between Two Values in Numpy

Modify Array Shape in Python

Now, I will explain some methods to modify array shapes in Python

Method 1: Use reshape()

Use reshape() to change the shape of a NumPy array without altering its data.

import numpy as np

# Create a 1D array with 12 elements
sales_data = np.array([120, 145, 160, 178, 195, 210, 199, 187, 170, 155, 140, 130])

# Reshape into quarterly data for 3 years
sales_reshaped = sales_data.reshape(3, 4)
print("Quarterly sales over 3 years:")
print(sales_reshaped)
print("New shape:", sales_reshaped.shape)

Output:

Quarterly sales over 3 years:
[[120 145 160 178]
 [195 210 199 187]
 [170 155 140 130]]
New shape: (3, 4)

I executed the above example code and added the screenshot below.

python shape

reshape() is ideal when you need a new array structure without modifying the original array in place.

Check out Create a Python Empty Matrix

Method 2: Use resize()

The resize() method reshapes a NumPy array in-place, permanently modifying its structure.

import numpy as np

sales_data = np.array([120, 145, 160, 178, 195, 210, 199, 187, 170, 155, 140, 130])
sales_data.resize(4, 3)
print("Resized sales data:")
print(sales_data)
print("New shape:", sales_data.shape)

Output:

Resized sales data:
[[120 145 160]
 [178 195 210]
 [199 187 170]
 [155 140 130]]
New shape: (4, 3)

Use resize() when you want to overwrite the existing array with a new shape directly.

Method 3: Use -1 in reshape()

Using -1 in reshape() lets NumPy automatically calculate one of the dimensions.

import numpy as np

# Create a 1D array with 12 elements
sales_data = np.array([120, 145, 160, 178, 195, 210, 199, 187, 170, 155, 140, 130])

# Reshape into rows of 3 (letting NumPy figure out how many rows we need)
sales_reshaped = sales_data.reshape(-1, 3)
print(sales_reshaped)
print("Shape:", sales_reshaped.shape)

Output:

[[120 145 160]
 [178 195 210]
 [199 187 170]
 [155 140 130]]
Shape: (4, 3)

This technique is perfect for reshaping arrays when you’re unsure of one dimension’s size.

Get Dimension Information

Let me explain how to get dimension information.

Read NumPy Reset Index of an Array in Python

Total Elements with size

The .size attribute in NumPy returns the total number of elements across all dimensions of an array.

import numpy as np

temperature_data = np.array([
    [45, 32, 68],
    [47, 34, 70],
    [49, 35, 71],
    [51, 36, 73],
    [53, 37, 75]
])

print("Shape:", temperature_data.shape)
print("Total elements:", temperature_data.size)

Output:

Shape: (5, 3)
Total elements: 15

Use .size to easily determine how much data an array holds, regardless of its shape.

Number of Dimensions with ndim

Use the .ndim attribute in NumPy to quickly find out how many dimensions an array has.

import numpy as np

# 1D array
array_1d = np.array([1, 2, 3, 4, 5])
print("1D array dimensions:", array_1d.ndim)

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

# 3D array
array_3d = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
print("3D array dimensions:", array_3d.ndim)

Output:

1D array dimensions: 1
2D array dimensions: 2
3D array dimensions: 3

The .ndim property is a simple way to inspect the structure of any NumPy array.

Practical Applications

Let me explain to you some practical examples that will help you to understand more about the NumPy shape.

Check out np.genfromtxt() Function in Python

Check Input Data Shape

One common use of shape is to validate input data:

import numpy as np

def process_monthly_data(data):
    # Check if the data has 12 months
    if data.shape[0] != 12:
        raise ValueError(f"Expected 12 months of data, got {data.shape[0]}")

    # Process data here
    return data.mean()

# Test with correct data
monthly_sales = np.random.randint(1000, 5000, size=12)
print("Average monthly sales:", process_monthly_data(monthly_sales))

# Test with incorrect data
try:
    quarterly_sales = np.random.randint(1000, 5000, size=4)
    process_monthly_data(quarterly_sales)
except ValueError as e:
    print("Error:", e)

Data Transformation for Machine Learning

Shape manipulation is crucial for preparing data for machine learning:

import numpy as np

# Imagine we have image data for a classification task
# 100 images, each 28x28 pixels
image_data = np.random.random((100, 28, 28))
print("Original image data shape:", image_data.shape)

# Many ML algorithms need flat vectors as input
# Reshape to (100, 784) - keeping each image as a row, flattening the pixels
flat_data = image_data.reshape(100, -1)
print("Flattened data shape:", flat_data.shape)

Output:

Original image data shape: (100, 28, 28)
Flattened data shape: (100, 784)

Common Shape Errors and Solutions

Let me show you some common shape errors and also the solutions to overcome.

Read np.savetxt() Function in Python

Broadcast Issues

NumPy’s broadcasting allows operations between arrays of different shapes, but sometimes leads to errors:

import numpy as np

# US sales data (5 regions, 4 quarters)
us_sales = np.random.randint(100, 1000, size=(5, 4))

# Quarterly adjustment factors
adjustments = np.array([1.1, 0.9, 1.0, 1.2])

# This works - broadcasting happens correctly
adjusted_sales = us_sales * adjustments
print("Original shape:", us_sales.shape)
print("Adjustment shape:", adjustments.shape)
print("Result shape:", adjusted_sales.shape)

# This would fail - shapes are incompatible
try:
    incompatible = np.array([1.1, 0.9, 1.0])  # Only 3 values
    us_sales * incompatible
except ValueError as e:
    print("Error:", e)

Flattening vs. Reshaping

Understanding the difference between flatten and reshape(-1) is important:

import numpy as np

matrix = np.array([[1, 2, 3], [4, 5, 6]])
print("Original matrix:", matrix)
print("Original shape:", matrix.shape)

# flatten() returns a copy
flattened = matrix.flatten()
print("Flattened array:", flattened)
print("Flattened shape:", flattened.shape)

# reshape returns a view when possible
reshaped = matrix.reshape(-1)
print("Reshaped array:", reshaped)
print("Reshaped shape:", reshaped.shape)

# Demonstrating the difference (view vs. copy)
flattened[0] = 99
reshaped[1] = 88
print("\nAfter modification:")
print("Original matrix:", matrix)  # Only affected by reshape changes
print("Flattened array:", flattened)
print("Reshaped array:", reshaped)

Both methods will help you get a 1D array, but reshape provides a view (changes affect the original) while flatten gives you a copy.

Conclusion

Understanding NumPy’s shape attribute is essential for efficient data manipulation in Python. I covered the basic usage of NumPy shape, modifying array shape, how to get dimension information, some practical applications, and common shape errors and solutions.

The key things to remember are:

  • Shape is returned as a tuple representing the size of each dimension
  • You can modify shapes using reshape() or resize()
  • Use -1 in reshape() to automatically calculate one dimension
  • Always verify your data’s shape before performing operations

Other related tutorials:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.