How numpy ravel works in Python? Best example

How numpy ravel works in Python? Best example
“`html

Understanding numpy.ravel() in Python

Working with multidimensional arrays in NumPy is a fundamental aspect of data science, machine learning, and numerical computing. Often, we need to flatten an array to a one-dimensional representation. That’s where numpy.ravel() comes in handy. But how does it actually work? Let’s dive deep into the function and understand it with an example.

What Is numpy.ravel()?

The numpy.ravel() function returns a flattened array, meaning it reduces a multidimensional array to a one-dimensional array. Unlike some other flattening methods in NumPy, ravel() tries to return a view of the original array whenever possible instead of creating a completely separate copy.

Basic Syntax

Before jumping into examples, let’s understand its syntax.


numpy.ravel(a, order='C')

Where:

  • a – The input array.
  • order – The order in which to read the elements (‘C’ for row-major, ‘F’ for column-major, ‘A’ to decide automatically, and ‘K’ to preserve the input order as much as possible).

Example: How numpy.ravel() Works?

To truly understand numpy.ravel(), let’s look at an example.


import numpy as np

# Creating a 2D NumPy array
arr = np.array([[1, 2, 3], 
                [4, 5, 6]])

# Using ravel to flatten it
flattened = np.ravel(arr)

print("Original array:")
print(arr)

print("\nFlattened array:")
print(flattened)

Output:


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

Flattened array:
[1 2 3 4 5 6]

Understanding Views vs Copies

One key difference between numpy.ravel() and numpy.flatten() is that ravel() returns a view of the original array whenever possible. This means that modifying the flattened array might also affect the original array.


flat_view = arr.ravel()
flat_view[0] = 99

print("Modified flattened array:")
print(flat_view)

print("\nOriginal array after modification:")
print(arr)

Output:


Modified flattened array:
[99  2  3  4  5  6]

Original array after modification:
[[99  2  3]
 [ 4  5  6]]

This happens because flat_view is not a new copy but a view of arr. If we used flatten() instead, a completely independent copy would be created.

Comparison: ravel() vs flatten()

Let’s quickly compare numpy.ravel() with numpy.flatten():

Function Returns Modifying Affects Original?
numpy.ravel() View (if possible), otherwise a copy Yes, if it returns a view
numpy.flatten() Always a new copy No, original remains unchanged

Different Flattering Orders

The order parameter lets us specify how the elements are ordered in the one-dimensional output.


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

print("Row-major order (C-style):", np.ravel(arr, order='C'))
print("Column-major order (Fortran-style):", np.ravel(arr, order='F'))

Output:


Row-major order (C-style): [1 2 3 4 5 6]
Column-major order (Fortran-style): [1 4 2 5 3 6]

When to Use numpy.ravel()?

Here are some common scenarios where numpy.ravel() is useful:

  1. Flattening arrays for machine learning models (many ML libraries require 1D input).
  2. Reducing multi-dimensional arrays for easier data manipulation.
  3. Performance optimization – using a view rather than an expensive copy.

Conclusion

Now you know how numpy.ravel() works in Python! It provides an efficient way to flatten arrays while trying to return a view instead of a full copy. Understanding how it differs from numpy.flatten() is crucial to writing memory-efficient and high-performance NumPy code.

“` Other interesting article: How numpy reshape works in Python? Best example