Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between flatten and ravel in numpy? [duplicate]

Tags:

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?

like image 613
Bryan P Avatar asked Mar 03 '15 16:03

Bryan P


People also ask

What is the difference between flattening and reshaping an array?

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.

What does flatten () do in numpy?

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.

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 does the Ravel function do?

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

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.

like image 93
Bryan P Avatar answered Oct 24 '22 16:10

Bryan P