0
0
Data Analysis Pythondata~5 mins

Array shapes and dimensions in Data Analysis Python

Choose your learning style9 modes available
Introduction

We use array shapes and dimensions to understand the size and structure of data. This helps us organize and analyze data correctly.

When checking if data fits together for calculations
When reshaping data to prepare for analysis
When debugging errors caused by mismatched data sizes
When summarizing data to understand its layout
When visualizing data to know how many axes to plot
Syntax
Data Analysis Python
import numpy as np

# Create an array
array = np.array([[1, 2, 3], [4, 5, 6]])

# Get the shape of the array
shape = array.shape

# Get the number of dimensions
dimensions = array.ndim

shape returns a tuple showing the size in each dimension.

ndim returns an integer showing how many dimensions the array has.

Examples
Empty array has shape (0,) and 1 dimension.
Data Analysis Python
import numpy as np

empty_array = np.array([])
print(empty_array.shape)  # Output: (0,)
print(empty_array.ndim)   # Output: 1
Array with one element has shape (1,) and 1 dimension.
Data Analysis Python
import numpy as np

one_element_array = np.array([42])
print(one_element_array.shape)  # Output: (1,)
print(one_element_array.ndim)   # Output: 1
2D array (matrix) with 2 rows and 3 columns.
Data Analysis Python
import numpy as np

matrix = np.array([[1, 2, 3], [4, 5, 6]])
print(matrix.shape)  # Output: (2, 3)
print(matrix.ndim)   # Output: 2
3D array (tensor) with shape showing 3 dimensions.
Data Analysis Python
import numpy as np

tensor = np.array([[[1], [2]], [[3], [4]]])
print(tensor.shape)  # Output: (2, 2, 1)
print(tensor.ndim)   # Output: 3
Sample Program

This program creates arrays with different shapes and dimensions. It prints their shapes and number of dimensions to show how data structure changes.

Data Analysis Python
import numpy as np

# Create different arrays
empty_array = np.array([])
one_element_array = np.array([42])
matrix = np.array([[1, 2, 3], [4, 5, 6]])
tensor = np.array([[[1], [2]], [[3], [4]]])

# Print shapes and dimensions
print(f"Empty array shape: {empty_array.shape}, dimensions: {empty_array.ndim}")
print(f"One element array shape: {one_element_array.shape}, dimensions: {one_element_array.ndim}")
print(f"Matrix shape: {matrix.shape}, dimensions: {matrix.ndim}")
print(f"Tensor shape: {tensor.shape}, dimensions: {tensor.ndim}")
OutputSuccess
Important Notes

Time complexity to get shape or ndim is O(1) because it is stored as metadata.

Space complexity is not affected by accessing shape or ndim.

Common mistake: Confusing shape (size in each dimension) with total number of elements.

Use shape and ndim to check if arrays can be combined or reshaped safely.

Summary

Array shape tells how many elements are in each dimension.

Number of dimensions shows how many axes the data has.

Knowing shape and dimensions helps organize and analyze data correctly.