6

Often, when numpy has seemingly duplicate functions, there often ends up being some sort of unique purpose for one or the other.

I am trying to figure out if there are any situations where flatten() should be used instead of reshape(-1)

SantoshGupta7
  • 5,607
  • 14
  • 58
  • 116
  • 3
    There's another choice, `np.ravel` (and its method). I tend to prefer it; it's closer to the `reshape` in behavior. – hpaulj Sep 09 '19 at 00:10

1 Answers1

9

flatten returns a copy of the array. reshape will return a view if possible. So, for example, if y = x.reshape(-1) is a view, then modifying y also modifies x:

In [149]: x = np.arange(3)

In [150]: y = x.reshape(-1)

In [151]: y[0] = 99

In [152]: x
Out[152]: array([99,  1,  2])

But since y = x.flatten() is a copy, modifying y will never modify x:

In [153]: x = np.arange(3)

In [154]: y = x.flatten()

In [155]: y[0] = 99

In [156]: x
Out[156]: array([0, 1, 2])

Here is an example of when reshape returns a copy instead of a view:

In [161]: x = np.arange(24).reshape(4,6)[::2, :]

In [163]: y = x.reshape(-1)

In [164]: y[0] = 99

In [165]: x
Out[165]: 
array([[ 0,  1,  2,  3,  4,  5],
       [12, 13, 14, 15, 16, 17]])

Since x is unaffected by an assignment made to y, we know y is a copy of x, not a view.

unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
  • So there 3rd example is fictional, for the purpose of demonstrating the difference between a view and copy? It is not possible for reshape to return a copy? – SantoshGupta7 Sep 08 '19 at 23:16
  • It's not fiction. (But don't take my word for it; try the example yourself!) `x.reshape(-1)` can return a copy, in particular, when there is no single constant that can describe the [stride of the 1D array](https://stackoverflow.com/q/53097952/190597). – unutbu Sep 08 '19 at 23:34
  • 1
    @SantoshGupta7, `np.reshape` documents the alternative `arr.shape=-1` which acts in-place, and raises an error if a no-copy reshape is impossible. – hpaulj Sep 09 '19 at 01:51
  • What about expand_dims()? – skan Jan 25 '23 at 19:52