Numpy v 1.9 contains two seemingly identical functions: 'flatten' and 'ravel'
What is the difference? and when might I pick one vs the other for converting a 2-D np.array to 1-D?
It is essential because when we reshape an array, the reshape function is first going to flatten the input, and then split it into new arrays. Flattened means that we get rid of all squared brackets and return the array elements one by one enclosed in a single array.
The flatten() function is used to get a copy of an given array collapsed into one dimension. 'C' means to flatten in row-major (C-style) order. 'F' means to flatten in column-major (Fortran- style) order. 'A' means to flatten in column-major order if a is Fortran contiguous in memory, row-major order otherwise.
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.
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.
Aha: The primary functional difference is thatflatten
is a method of an ndarray object and hence can only be called for true numpy arrays. In contrast ravel()
is a library-level function and hence can be called on any object that can successfully be parsed. For example ravel()
will work on a list of ndarrays, while flatten (obviously) won't.
In addition, as @jonrsharpe pointed out in his comment, the flatten method always returns a copy, while ravel only does so "if needed." Still not quite sure how this determination is made.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With