[Numpy-discussion] Why ndarray provides four ways to flatten?

Alexander Belopolsky 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
>>> i.next()
0
>>> i.next()
1
>>> i.next()
2

So far no surprises, but what should i[0] return now?  If you think of i as
a C pointer you would expect 3, but

>>> i[0]
0

What is worse, the above resets the index and now

>>> i.index
0

OK, so now I expect that i[5] will reset the index to 5, but no

>>> i[5]
5
>>> i.index
0

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(),
only slower?

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

>>> np.hstack(x)
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

>>> np.hstack(np.hstack(y))
array([0, 1, 0, 1, 0, 1, 2, 0, 1, 0, 1, 2, 0, 1, 2, 3])

?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20141028/16417edd/attachment.html>


More information about the NumPy-Discussion mailing list