Numpy : Difference between flatten and raveal

Numpy : Difference between flatten and raveal

In NumPy, both the flatten() and ravel() functions are used to convert multidimensional arrays into one-dimensional arrays. However, there are a few differences between these two functions:

  1. Return Type: The flatten() function returns a copy of the array, while the ravel() function returns a view of the original array whenever possible. A view is a reference to the original data, whereas a copy creates a new array with its own data.
  2. Memory Contiguity: The flatten() function always returns a copy of the array, which means the resulting array is guaranteed to be memory contiguous. On the other hand, the ravel() function returns a view whenever possible, which may or may not be contiguous depending on the original array's memory layout.
  3. Performance: Since ravel() returns a view whenever possible, it is generally faster and more memory-efficient compared to flatten(), which always creates a new array. However, if a contiguous array is required, flatten() is a safer choice.
  4. Modifying Original Array: If modifications are made to the flattened or raveled array, the behavior differs. Changes to the flattened array do not affect the original array, as it is a copy. However, changes to the raveled array may alter the original array, as it is a view referring to the same data.

Here's an example to illustrate these differences:


import numpy as np


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


# Using flatten()
flattened = arr.flatten()
flattened[0] = 10? # Modifying the flattened array


# Using ravel()
raveled = arr.ravel()
raveled[0] = 20? # Modifying the raveled array


print(arr)
print(flattened)
print(raveled)        

Output :

[[1 2 3]
?[4 5 6]]
[10? 2? 3? 4? 5? 6]
[20? 2? 3? 4? 5? 6]        

In the example, modifying the flattened array does not change the original arr. However, modifying the raveled array also modifies the original arr because it is a view sharing the same data.

Overall, the main differences between flatten() and ravel() in NumPy are related to return types (copy vs. view), memory contiguity, performance, and their impact on modifying the original array.

要查看或添加评论,请登录

Yeshwanth Nagaraj的更多文章

社区洞察

其他会员也浏览了