Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between flatten and ravel functions in numpy?

import numpy as np y = np.array(((1,2,3),(4,5,6),(7,8,9))) OUTPUT: print(y.flatten()) [1   2   3   4   5   6   7   8   9] print(y.ravel()) [1   2   3   4   5   6   7   8   9] 

Both function return the same list. Then what is the need of two different functions performing same job.

like image 697
cryptomanic Avatar asked Mar 08 '15 18:03

cryptomanic


People also ask

Is Ravel same as flatten?

(iii) Ravel is faster than flatten() as it does not occupy any memory. (iv) Ravel is a library-level function. (ii) If you modify any value of this array value of original array is not affected. (iii) Flatten() is comparatively slower than ravel() as it occupies memory.

What does Ravel mean in numpy?

The numpy. ravel() functions returns contiguous flattened array(1D array with all the input-array elements and with the same type as it). A copy is made only if needed.

What is flatten in numpy?

flatten(order='C') Return a copy of the array collapsed into one dimension. Parameters order{'C', 'F', 'A', 'K'}, optional. 'C' means to flatten in row-major (C-style) order.

Why do we use Ravel function?

The ravel() function is used to create a contiguous flattened array. A 1-D array, containing the elements of the input, is returned. A copy is made only if needed. Input array.


1 Answers

The current API is that:

  • flatten always returns a copy.
  • ravel returns a view of the original array whenever possible. This isn't visible in the printed output, but if you modify the array returned by ravel, it may modify the entries in the original array. If you modify the entries in an array returned from flatten this will never happen. ravel will often be faster since no memory is copied, but you have to be more careful about modifying the array it returns.
  • reshape((-1,)) gets a view whenever the strides of the array allow it even if that means you don't always get a contiguous array.
like image 200
IanH Avatar answered Sep 30 '22 18:09

IanH