What is flatten() in NumPy?
In NumPy, flatten()
is a method used to transform a multi-dimensional array into a one-dimensional array. It's especially useful when you need a flat sequence of values from a matrix or tensor-like structure, such as when feeding data into machine learning models or simplifying output for reporting.
When should you use flatten()?
Use flatten()
when you want to create a copy of your array data in one dimension. This is helpful when you’re doing operations that should not affect the original array or when reshaping is not an option due to inconsistent dimensions.
Basic Syntax
flattened_array = original_array.flatten()
The method returns a new 1D array with all the elements of the input array.
Example: Flattening a 2D Array
import numpy as np
matrix = np.array([[1, 2], [3, 4], [5, 6]])
flat = matrix.flatten()
print("Original:
", matrix)
print("Flattened:", flat)
Output Explanation
Original:
[[1 2]
[3 4]
[5 6]]
Flattened: [1 2 3 4 5 6]
Here, the original array has a shape of (3, 2)
. After using flatten()
, we get a 1D array with shape (6,)
. Importantly, flatten()
returns a copy, not a view.
Check: Is the Result a View or a Copy?
flat[0] = 99
print("Modified Flattened:", flat)
print("Original After Modification:
", matrix)
Output
Modified Flattened: [99 2 3 4 5 6]
Original After Modification:
[[1 2]
[3 4]
[5 6]]
As you can see, the original matrix remains unchanged. This confirms that flatten()
creates a separate copy in memory.
Common Pitfall: Using flatten() When Memory Efficiency Matters
Since flatten()
always returns a copy, it consumes extra memory. If your array is large and you don’t need to keep the original intact, consider using ravel()
instead—it returns a view when possible.
Best Practice
- Use
flatten()
when you need an independent, one-dimensional copy of the array. - Use
ravel()
when you are memory-conscious and can work with views. - Double-check the shape before and after flattening to verify results, especially when chaining array transformations.
Summary
The flatten()
method in NumPy is a straightforward yet powerful tool for transforming arrays into 1D formats. Whether you’re preprocessing data or simplifying structures for output, it provides a clean, safe way to flatten arrays without altering the source. Just remember—you're working with a copy, not a view.
Quick Recap
- Method:
arr.flatten()
- Returns: 1D array (copy)
- Does it affect original? No
- Use Case: When you need a flat copy of array data