Skip to content

Python NumPy: How to Flatten a Matrix in Python Using NumPy

Learn how to flatten a NumPy matrix into a 1D array using flatten(), ravel(), or reshape(-1), with explanations of the order parameter and memory efficiency trade-offs.

Flattening a matrix means converting a multi-dimensional array into a one-dimensional array. This is a fundamental operation in data processing, machine learning, and image manipulation - anytime you need to transform structured grid data into a flat sequence of values.

NumPy provides the flatten() method for this purpose, along with alternatives like ravel() and reshape(-1). This guide covers how each works, explains the order parameter, and helps you choose the right method for your use case.

The flatten() method returns a new 1D array that is a copy of the original matrix's elements. By default, elements are read row by row (row-major order).

import numpy as np

matrix = np.array([
    [10, 20, 30],
    [40, 50, 60]
])

flat = matrix.flatten()

print("Original matrix:")
print(matrix)
print("\nFlattened:", flat)

Output:

Original matrix:
[[10 20 30]
 [40 50 60]]

Flattened: [10 20 30 40 50 60]

The elements are read left to right, top to bottom - row 1 first (10, 20, 30), then row 2 (40, 50, 60).

Understanding the order Parameter

The order parameter controls how elements are read from the matrix during flattening.

Syntax:

ndarray.flatten(order='C')

Row-Major Order (order='C') - Default

Elements are read row by row, which is the default behavior and matches how most Python/C programs store arrays in memory:

import numpy as np

matrix = np.array([
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
])

print("Row-major (C):", matrix.flatten(order='C'))

Output:

Row-major (C): [1 2 3 4 5 6 7 8 9]

Column-Major Order (order='F')

Elements are read column by column, matching how Fortran stores arrays in memory:

import numpy as np

matrix = np.array([
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
])

print("Column-major (F):", matrix.flatten(order='F'))

Output:

Column-major (F): [1 4 7 2 5 8 3 6 9]

Elements are read top to bottom for each column: column 1 (1, 4, 7), column 2 (2, 5, 8), column 3 (3, 6, 9).

Visual Comparison of Orders

import numpy as np

matrix = np.array([
    [1, 2, 3],
    [4, 5, 6]
])

print("Original:")
print(matrix)
print()
print("order='C' (row-major):   ", matrix.flatten(order='C'))
print("order='F' (column-major):", matrix.flatten(order='F'))

Output:

Original:
[[1 2 3]
 [4 5 6]]

order='C' (row-major):    [1 2 3 4 5 6]
order='F' (column-major): [1 4 2 5 3 6]

All Order Options

Order Description
'C' Row-major (C-style) - reads row by row (default)
'F' Column-major (Fortran-style) - reads column by column
'A' Uses 'F' if the array is Fortran-contiguous in memory, otherwise 'C'
'K' Reads elements in the order they appear in memory

flatten() vs ravel() vs reshape(-1)

NumPy offers three ways to flatten an array. The key difference is whether the result is a copy or a view of the original data.

flatten() - Always Returns a Copy

import numpy as np

matrix = np.array([[1, 2], [3, 4]])
flat = matrix.flatten()

flat[0] = 99
print("Original:", matrix)
print("Flattened:", flat)

Output:

Original: [[1 2]
 [3 4]]
Flattened: [99  2  3  4]

ravel() - Returns a View When Possible

import numpy as np

matrix = np.array([[1, 2], [3, 4]])
flat = matrix.ravel()

flat[0] = 99
print("Original:", matrix)
print("Raveled:", flat)

Output:

Original: [[99  2]
 [ 3  4]]
Raveled: [99  2  3  4]

reshape(-1) - Also Returns a View When Possible

import numpy as np

matrix = np.array([[1, 2], [3, 4]])
flat = matrix.reshape(-1)

flat[0] = 99
print("Original:", matrix)
print("Reshaped:", flat)

Output:

Original: [[99  2]
 [ 3  4]]
Reshaped: [99  2  3  4]

Comparison Summary

Method Returns Safe to Modify? Memory Efficient
flatten() Always a copy ✅ Yes ❌ Uses extra memory
ravel() View when possible ⚠️ May affect original ✅ No extra memory
reshape(-1) View when possible ⚠️ May affect original ✅ No extra memory

Flattening Higher-Dimensional Arrays

flatten() works on arrays of any number of dimensions, not just 2D matrices:

import numpy as np

arr_3d = np.array([
    [[1, 2, 3], [4, 5, 6]],
    [[7, 8, 9], [10, 11, 12]]
])

print("Shape:", arr_3d.shape)
print("Flattened:", arr_3d.flatten())

Output:

Shape: (2, 2, 3)
Flattened: [ 1  2  3  4  5  6  7  8  9 10 11 12]

Practical Example: Flattening an Image Matrix

A common real-world use case is flattening image pixel data for machine learning models:

import numpy as np

image = np.array([
    [200, 150, 100, 50],
    [180, 130, 80, 30],
    [160, 110, 60, 10],
    [140, 90, 40, 0]
], dtype=np.uint8)

feature_vector = image.flatten()

print(f"Image shape: {image.shape}")
print(f"Feature vector shape: {feature_vector.shape}")
print(f"Feature vector: {feature_vector}")

Output:

Image shape: (4, 4)
Feature vector shape: (16,)
Feature vector: [200 150 100  50 180 130  80  30 160 110  60  10 140  90  40   0]

Conclusion

Flattening a matrix in NumPy is straightforward with flatten(), which always returns a safe, independent copy of the data as a 1D array.

  • Use the order parameter to control whether elements are read row by row ('C') or column by column ('F').
  • For memory-efficient flattening where you don't need a copy, consider ravel() or reshape(-1), but be aware that modifying the result may affect the original array.
  • Choose the method that matches your needs for safety versus performance.
Navigation