Flattening NumPy arrays
Start your free 7-days trial now!
We can reduce a n-dimensional NumPy array to 1D using either the flatten()
or ravel()
method available to all NumPy arrays. We first demonstrate their usages, and subsequently their differences.
Example
Consider the following 2 by 3 array:
array([[1, 2, 3], [4, 5, 6]])
We can use the flatten
method as follows:
array([1, 2, 3, 4, 5, 6])
We can also use the ravel
method:
array([1, 2, 3, 4, 5, 6])
Notice the outputs are the same - we end up with a one-dimensional flattened array.
Difference between flatten and ravel
The flatten(~)
returns a separate copy of the NumPy array. This means that making modification on the original array would not have any impact on the flattened array. Just to illustrate, study the following code:
On the other hand, the ravel(~)
returns a NumPy array that shares the same memory address as the original array:
As arrays x
and y
both share the same memory address, when we update value [0,0]
in array x
, we can see that the new assignment of 9
is reflected in array y
also.
In terms of speed and memory-savings, ravel()
is superior. Therefore, use ravel()
if you are certain that:
you won't need the original array
you won't make any modification on the original array
You should also be reminded that, unless we are dealing with large amounts of data, the performance difference is negligible. Therefore, you may want to use flatten()
to ensure that nothing out of the ordinary happens.