[Numpy-discussion] Why ndarray provides four ways to flatten?
ndarray at mac.com
Tue Oct 28 12:58:08 EDT 2014
On Mon, Oct 27, 2014 at 9:41 PM, Yuxiang Wang <yw5aj at virginia.edu> wrote:
> In my opinion - because they don't do the same thing, especially when
> you think in terms in lower-level.
> ndarray.flat returns an iterator; ndarray.flatten() returns a copy;
> ndarray.ravel() only makes copies when necessary; ndarray.reshape() is
> more general purpose, even though you can use it to flatten arrays.
Out of the four ways, I find x.flat the most confusing. Unfortunately, it
is also the most obvious name for the operation (and "ravel" is the least,
but it is the fault of the English language where "to ravel" means "to
unravel."). What x.flat returns, is not really an iterator. It is some
hybrid between a view and an iterator. Consider this:
>>> x = numpy.arange(6).reshape((2,3))
>>> i = x.flat
So far no surprises, but what should i return now? If you think of i as
a C pointer you would expect 3, but
What is worse, the above resets the index and now
OK, so now I expect that i will reset the index to 5, but no
When would you prefer to use x.flat over x.ravel()?
Is x.reshape(-1) always equivalent to x.ravel()?
What is x.flat.copy()? Is it the same as x.flatten()? Why does flatiter
even have a .copy() method? Isn't i.copy() the same as i.base.flatten(),
And with all these methods, I still don't have the one that would flatten
any array including a nested array like this:
>>> x = np.array([np.arange(2), np.arange(3), np.arange(4)])
I need yet another function here, for example
array([0, 1, 0, 1, 2, 0, 1, 2, 3])
and what if I want to flatten a higher dimensional nested array, say
>>> y = np.array([x[:1],x[:2],x])
can I do better than
array([0, 1, 0, 1, 0, 1, 2, 0, 1, 0, 1, 2, 0, 1, 2, 3])
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the NumPy-Discussion