We use array shapes and dimensions to understand the size and structure of data. This helps us organize and analyze data correctly.
Array shapes and dimensions in 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.
import numpy as np empty_array = np.array([]) print(empty_array.shape) # Output: (0,) print(empty_array.ndim) # Output: 1
import numpy as np one_element_array = np.array([42]) print(one_element_array.shape) # Output: (1,) print(one_element_array.ndim) # Output: 1
import numpy as np matrix = np.array([[1, 2, 3], [4, 5, 6]]) print(matrix.shape) # Output: (2, 3) print(matrix.ndim) # Output: 2
import numpy as np tensor = np.array([[[1], [2]], [[3], [4]]]) print(tensor.shape) # Output: (2, 2, 1) print(tensor.ndim) # Output: 3
This program creates arrays with different shapes and dimensions. It prints their shapes and number of dimensions to show how data structure changes.
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}")
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.
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.