
- NumPy - Home
- NumPy - Introduction
- NumPy - Environment
- NumPy Arrays
- NumPy - Ndarray Object
- NumPy - Data Types
- NumPy Creating and Manipulating Arrays
- NumPy - Array Creation Routines
- NumPy - Array Manipulation
- NumPy - Array from Existing Data
- NumPy - Array From Numerical Ranges
- NumPy - Iterating Over Array
- NumPy - Reshaping Arrays
- NumPy - Concatenating Arrays
- NumPy - Stacking Arrays
- NumPy - Splitting Arrays
- NumPy - Flattening Arrays
- NumPy - Transposing Arrays
- NumPy Indexing & Slicing
- NumPy - Indexing & Slicing
- NumPy - Indexing
- NumPy - Slicing
- NumPy - Advanced Indexing
- NumPy - Fancy Indexing
- NumPy - Field Access
- NumPy - Slicing with Boolean Arrays
- NumPy Array Attributes & Operations
- NumPy - Array Attributes
- NumPy - Array Shape
- NumPy - Array Size
- NumPy - Array Strides
- NumPy - Array Itemsize
- NumPy - Broadcasting
- NumPy - Arithmetic Operations
- NumPy - Array Addition
- NumPy - Array Subtraction
- NumPy - Array Multiplication
- NumPy - Array Division
- NumPy Advanced Array Operations
- NumPy - Swapping Axes of Arrays
- NumPy - Byte Swapping
- NumPy - Copies & Views
- NumPy - Element-wise Array Comparisons
- NumPy - Filtering Arrays
- NumPy - Joining Arrays
- NumPy - Sort, Search & Counting Functions
- NumPy - Searching Arrays
- NumPy - Union of Arrays
- NumPy - Finding Unique Rows
- NumPy - Creating Datetime Arrays
- NumPy - Binary Operators
- NumPy - String Functions
- NumPy - Matrix Library
- NumPy - Linear Algebra
- NumPy - Matplotlib
- NumPy - Histogram Using Matplotlib
- NumPy Sorting and Advanced Manipulation
- NumPy - Sorting Arrays
- NumPy - Sorting along an axis
- NumPy - Sorting with Fancy Indexing
- NumPy - Structured Arrays
- NumPy - Creating Structured Arrays
- NumPy - Manipulating Structured Arrays
- NumPy - Record Arrays
- Numpy - Loading Arrays
- Numpy - Saving Arrays
- NumPy - Append Values to an Array
- NumPy - Swap Columns of Array
- NumPy - Insert Axes to an Array
- NumPy Handling Missing Data
- NumPy - Handling Missing Data
- NumPy - Identifying Missing Values
- NumPy - Removing Missing Data
- NumPy - Imputing Missing Data
- NumPy Performance Optimization
- NumPy - Performance Optimization with Arrays
- NumPy - Vectorization with Arrays
- NumPy - Memory Layout of Arrays
- Numpy Linear Algebra
- NumPy - Linear Algebra
- NumPy - Matrix Library
- NumPy - Matrix Addition
- NumPy - Matrix Subtraction
- NumPy - Matrix Multiplication
- NumPy - Element-wise Matrix Operations
- NumPy - Dot Product
- NumPy - Matrix Inversion
- NumPy - Determinant Calculation
- NumPy - Eigenvalues
- NumPy - Eigenvectors
- NumPy - Singular Value Decomposition
- NumPy - Solving Linear Equations
- NumPy - Matrix Norms
- NumPy Element-wise Matrix Operations
- NumPy - Sum
- NumPy - Mean
- NumPy - Median
- NumPy - Min
- NumPy - Max
- NumPy Set Operations
- NumPy - Unique Elements
- NumPy - Intersection
- NumPy - Union
- NumPy - Difference
- NumPy Random Number Generation
- NumPy - Random Generator
- NumPy - Permutations & Shuffling
- NumPy - Uniform distribution
- NumPy - Normal distribution
- NumPy - Binomial distribution
- NumPy - Poisson distribution
- NumPy - Exponential distribution
- NumPy - Rayleigh Distribution
- NumPy - Logistic Distribution
- NumPy - Pareto Distribution
- NumPy - Visualize Distributions With Sea born
- NumPy - Matplotlib
- NumPy - Multinomial Distribution
- NumPy - Chi Square Distribution
- NumPy - Zipf Distribution
- NumPy File Input & Output
- NumPy - I/O with NumPy
- NumPy - Reading Data from Files
- NumPy - Writing Data to Files
- NumPy - File Formats Supported
- NumPy Mathematical Functions
- NumPy - Mathematical Functions
- NumPy - Trigonometric functions
- NumPy - Exponential Functions
- NumPy - Logarithmic Functions
- NumPy - Hyperbolic functions
- NumPy - Rounding functions
- NumPy Fourier Transforms
- NumPy - Discrete Fourier Transform (DFT)
- NumPy - Fast Fourier Transform (FFT)
- NumPy - Inverse Fourier Transform
- NumPy - Fourier Series and Transforms
- NumPy - Signal Processing Applications
- NumPy - Convolution
- NumPy Polynomials
- NumPy - Polynomial Representation
- NumPy - Polynomial Operations
- NumPy - Finding Roots of Polynomials
- NumPy - Evaluating Polynomials
- NumPy Statistics
- NumPy - Statistical Functions
- NumPy - Descriptive Statistics
- NumPy Datetime
- NumPy - Basics of Date and Time
- NumPy - Representing Date & Time
- NumPy - Date & Time Arithmetic
- NumPy - Indexing with Datetime
- NumPy - Time Zone Handling
- NumPy - Time Series Analysis
- NumPy - Working with Time Deltas
- NumPy - Handling Leap Seconds
- NumPy - Vectorized Operations with Datetimes
- NumPy ufunc
- NumPy - ufunc Introduction
- NumPy - Creating Universal Functions (ufunc)
- NumPy - Arithmetic Universal Function (ufunc)
- NumPy - Rounding Decimal ufunc
- NumPy - Logarithmic Universal Function (ufunc)
- NumPy - Summation Universal Function (ufunc)
- NumPy - Product Universal Function (ufunc)
- NumPy - Difference Universal Function (ufunc)
- NumPy - Finding LCM with ufunc
- NumPy - ufunc Finding GCD
- NumPy - ufunc Trigonometric
- NumPy - Hyperbolic ufunc
- NumPy - Set Operations ufunc
- NumPy Useful Resources
- NumPy - Quick Guide
- NumPy - Cheatsheet
- NumPy - Useful Resources
- NumPy - Discussion
- NumPy Compiler
NumPy - Array Shape
NumPy Array Shape
The shape of a NumPy array is a tuple of integers. Each integer in the tuple represents the size of the array along a particular dimension or axis. For example, an array with shape (3, 4) has 3 rows and 4 columns.
- For a 2D array, the shape is a tuple with two elements: number of rows, number of columns.
- For a 3D array, the shape is a tuple with three elements: depth, number of rows, number of columns.
- Higher-dimensional arrays follow the same pattern, with each dimension's size represented as an additional element in the tuple.
Accessing Array Shape
You can access the shape of a NumPy array using the shape attribute. This attribute returns a tuple of integers, each representing the size of the array along a particular dimension.
Example
In the following example, we are creating a 2D array and retrieving its shape using the NumPy "shape" attribute −
import numpy as np # Creating a 2D array array = np.array([[1, 2, 3], [4, 5, 6]]) # Accessing the shape print("Shape of the array:", array.shape) print("Number of dimensions:", array.ndim) print("Total number of elements:", array.size)
The shape (2, 3) indicates that the array has 2 rows and 3 columns. It is a two-dimensional array −
Shape of the array: (2, 3) Number of dimensions: 2 Total number of elements: 6
Changing Array Shape
Changing the shape of a NumPy array refers to transforming the dimensions of an array without altering its data. For instance, a one-dimensional array can be reshaped into a two-dimensional array or vice versa, as long as the total number of elements remains constant.
To reshape an array in NumPy, we use the reshape() function. This function returns a new view of the array with the specified shape if possible. If the reshape is not possible with a view, a copy of the array is created.
Example
In this example, we are changing the shape of a 2D array to 1D array by passing "-1" as an argument to the Numpy reshape() function. This automatically infer the size of one dimension −
import numpy as np # Creating a 2D array array_2d = np.array([[1, 2, 3], [4, 5, 6]]) print("Original 2D array:\n", array_2d) # Reshaping to a 1D array array_flattened = array_2d.reshape(-1) print("Flattened to 1D array:", array_flattened)
This will produce the following result −
Original 2D array: [[1 2 3] [4 5 6]] Flattened to 1D array: [1 2 3 4 5 6]
Handling Reshape Errors
Sometimes reshaping arrays in NumPy can lead to errors if not used correctly. This error occurs when you attempt to reshape an array into a shape that is incompatible with the total number of elements in the array.
The total number of elements must remain constant when reshaping. If the reshape operation is incompatible with the total number of elements, NumPy will raise a ValueError.
Example: Incompatible Shape Error
The incompatible shape error occurs when you attempt to reshape an array into a shape that is incompatible with the total number of elements in the array.
In the example below, the original array has "12" elements. Reshaping it into a shape "(3, 5)" requires 15 elements, which causes a ValueError −
import numpy as np # Creating an array with 12 elements array = np.arange(12) # Attempting to reshape into a shape that requires more elements try: reshaped_array = array.reshape((3, 5)) except ValueError as e: print("Error:", e)
Following is the output of the above code −
Error: cannot reshape array of size 12 into shape (3,5)
Example: Negative Dimension Error
Using -1 in the reshape dimensions tells NumPy to automatically calculate the size of that dimension. However, if the remaining dimensions don't align with the total number of elements, it will raise an error −
import numpy as np # Creating an array with 10 elements array = np.arange(10) # Attempting to reshape with an incompatible automatic dimension try: reshaped_array = array.reshape((2, -1, 4)) except ValueError as e: print("Error:", e)
The output obtained is as shown below −
Error: cannot reshape array of size 10 into shape (2,newaxis,4)
Example: Incorrect Dimension Specification
Specifying an incorrect or non-integer dimension value (e.g., a negative value other than -1, or a non-integer) can lead to errors −
import numpy as np # Creating an array with 16 elements array = np.arange(16) # Attempting to reshape with an invalid dimension try: reshaped_array = array.reshape((4, 4.5)) except ValueError as e: print("Error:", e)
After executing the above code, we get the following output −
Traceback (most recent call last): File "/home/cg/root/669f5fd83ed84/main.py", line 8, in <module> reshaped_array = array.reshape((4, 4.5)) TypeError: 'float' object cannot be interpreted as an integer