Reshape and Flatten Arrays
Learn how to change the structure of NumPy arrays, convert one-dimensional arrays into multidimensional arrays, and flatten arrays into a single dimension for analysis and processing.
1. Learning Objectives
By the end of this lesson, you will be able to:
- Understand the purpose of reshaping arrays.
- Use the
reshape()method. - Convert one-dimensional arrays into two-dimensional and three-dimensional arrays.
- Use
-1to infer a dimension automatically. - Flatten arrays using
flatten()andravel(). - Understand the difference between flattening and reshaping.
- Avoid common shape mismatch errors.
2. What Is Array Reshaping?
Array reshaping means changing the arrangement or dimensions of
elements without changing the total number of elements.
NumPy provides the reshape() method for this purpose.
For example, an array containing six elements can be arranged as a single row, two rows with three columns, or three rows with two columns.
Reshaping changes the array's structure, not its total element count.
3. Using reshape()
The reshape() method accepts the desired dimensions.
The product of the requested dimensions must equal the number of
elements in the original array.
Possible Results
| Expression | Shape | Structure |
|---|---|---|
values.reshape(2, 3) |
(2, 3) |
Two rows and three columns. |
values.reshape(3, 2) |
(3, 2) |
Three rows and two columns. |
values.reshape(1, 6) |
(1, 6) |
One row and six columns. |
values.reshape(6, 1) |
(6, 1) |
Six rows and one column. |
(6,) is different from a two-dimensional row array
with shape (1, 6).
4. Reshaping into Three Dimensions
NumPy can reshape arrays into three or more dimensions, provided the requested shape contains the same total number of elements. Three-dimensional arrays are often used to represent batches, image channels, or grouped datasets.
Expected output:
Interpreting the Shape
- The first dimension has 2 groups.
- Each group has 2 rows.
- Each row has 3 elements.
- The total number of elements is 2 × 2 × 3 = 12.
5. Using -1 for Automatic Dimension Inference
NumPy allows one dimension in reshape() to be specified
as -1. NumPy calculates that dimension automatically
using the total number of elements and the other requested dimensions.
In the first example, twelve elements arranged in three rows require four columns. In the second example, the result has twelve rows and one column.
-1 in a reshape operation. NumPy cannot infer the shape
if the requested dimensions are ambiguous or incompatible.
6. What Is Array Flattening?
Flattening converts a multidimensional array into a one-dimensional array. It is useful when a task requires all elements in a single sequence, such as preparing values for certain analysis workflows.
Expected output:
Flattening reduces the array to one dimension.
7. Using flatten()
The flatten() method returns a flattened copy of the
array. Changes made to the returned array do not change the original
array's elements.
Expected output:
flatten() when you
specifically need an independent one-dimensional copy.
8. Using ravel()
The ravel() method also returns a one-dimensional
representation of an array. It often returns a view when possible,
but it may return a copy depending on the array's layout and
requested order.
Expected output:
If ravel() returns a view, changes to that view may
affect the original array. Do not rely on it always returning a
view or always returning a copy.
9. flatten() vs ravel()
| Feature | flatten() | ravel() |
|---|---|---|
| Result | One-dimensional array. | One-dimensional array. |
| Copy or view | Returns a copy. | Returns a view when possible; otherwise a copy. |
| Memory use | Allocates a separate array for the result. | May avoid a copy when possible. |
| Use when | An independent flattened array is required. | A flattened representation is needed and avoiding a copy may help. |
flatten() is the
straightforward choice.
10. Reshape Order: C and F
NumPy supports different element-reading orders when reshaping or
flattening. The default order, 'C', follows
row-major indexing. The 'F' order follows
column-major indexing.
Expected output:
| Order | Element sequence | Meaning |
|---|---|---|
'C' |
1, 2, 3, 4, 5, 6 |
Read across rows. |
'F' |
1, 4, 2, 5, 3, 6 |
Read down columns. |
The order argument describes how elements are indexed and read for the operation. It does not necessarily mean that the underlying memory is physically stored in that order.
11. Common Reshape Errors
A reshape operation fails when the requested dimensions cannot accommodate the original number of elements.
How to Prevent Errors
- Check the original array's
size. - Calculate the product of the requested dimensions.
- Use
-1when one dimension should be inferred. - Check the resulting
shapebefore further processing.
12. Practical Activity
Activity: Reshape Student Marks
Samadhan, Pradnya, and Samiksha are analyzing twelve marks stored in a one-dimensional array. Arrange the marks into a three-by-four matrix, then convert the matrix back into a one-dimensional array.
Tasks:
- Create an array containing twelve integer marks.
- Reshape the array into three rows and four columns.
- Print the reshaped array and its shape.
- Flatten the array using
flatten(). - Use
ravel()and compare the output.
Sample Solution
Expected key results:
- Reshaped array shape:
(3, 4) - Total elements:
12 - Flattened shape:
(12,) - Both flattening methods produce the same values in the default order.
Summary
reshape()changes an array's dimensions without changing its element count.- Every requested shape must be compatible with the original size.
-1allows NumPy to infer one dimension automatically.flatten()creates an independent one-dimensional copy.ravel()returns a one-dimensional array and may return a view when possible.- The
'C'and'F'orders determine how elements are indexed during the operation.
Reshaping and flattening help organize array data for mathematical operations, analysis, and machine learning workflows.