How to flatten only some dimensions of a numpy array
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.
Introduction
Flattening only some dimensions of a NumPy array really means reshaping selected axes into one combined axis while leaving the others intact. The operation is straightforward once you think in terms of shape algebra instead of “flatten” as an all-or-nothing action.
Flatten Contiguous Axes With reshape
If the axes you want to combine are adjacent, reshape is usually enough. For example, suppose an array has shape (2, 3, 4) and you want to merge the last two axes into one axis of size 12.
The logic is simple: 3 * 4 = 12, so the new shape becomes (2, 12).
You can do the same with the first two axes:
Here 2 * 3 = 6, so the result shape is (6, 4).
Use -1 When One Dimension Is Implied
NumPy can infer one dimension automatically with -1, which makes shape changes less error-prone.
This says “keep the first axis as it is and flatten everything else.” It is especially useful when the exact shape is not hardcoded.
Non-Adjacent Axes Need Reordering First
If the axes you want to combine are not next to each other, move them together first with transpose or moveaxis, then reshape.
Suppose the shape is (2, 3, 4, 5) and you want to combine axes 0 and 2 while leaving the others logically separate. Since those axes are not adjacent, reorder them first.
After reordering, axes 0 and 2 from the original array sit next to each other as the first two axes in reordered, so they can be merged cleanly into 8.
A Practical Mental Model
A useful way to reason about the operation is:
- decide the axis order you want
- move those axes into adjacent positions if necessary
- multiply the sizes of the axes you want to combine
- call
reshape
Once you do that, selective flattening is just controlled reshaping.
Views Versus Copies
reshape often returns a view when memory layout permits it, which is efficient. But after certain transposes or slices, the array may no longer be contiguous in the way reshape expects, and NumPy may need to create a copy.
You can inspect this with the flags attribute.
For correctness, this usually does not matter. For large arrays, it can matter a lot for memory use and speed.
A Reusable Helper Function
If you perform this kind of operation often, a helper can make the intent clearer.
This function flattens a contiguous block of axes, which covers many practical tensor reshaping tasks.
Common Use Cases
Selective flattening appears often in scientific and machine learning code:
- combine spatial dimensions before feeding data into a dense layer
- collapse batch and time axes for vectorized processing
- flatten image height and width while preserving channel count
- reshape grouped measurements into a 2D analysis matrix
The operation is not special to NumPy. It is a general tensor manipulation pattern.
Common Pitfalls
A common mistake is using flatten() when you only meant to merge some axes. flatten() always returns a fully 1D copy.
Another mistake is forgetting that non-adjacent axes cannot be merged directly without reordering the shape first.
Developers also miscompute the target size manually. Let NumPy infer one dimension with -1 where possible.
Finally, watch memory layout when working with very large arrays. A transpose followed by reshape may create a copy, which can be expensive.
Summary
- Flattening some dimensions is usually just
reshapeon selected axes. - Merge adjacent axes directly by multiplying their sizes.
- Reorder non-adjacent axes first with
transposeormoveaxis. - Use
-1when NumPy can infer one dimension safely. - Be aware that some reshape operations after transposition may allocate a copy.
Related reading
- How to form tuple column from two columns in Pandas
- How to generate a train-test-split based on a group id?
- How to get a colorbar in networkx.draw_networkx?
- How to get a normal distribution within a range in numpy?
- How to flatten tree via LINQ?
- How to for each the hashmap?
- How to format a floating number to fixed width in Python
- How to generate a temporary url to upload file to Amazon S3 with boto library?

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.