# [Numpy-discussion] summarizing blocks of an array using a moving window

Keith Goodman kwgoodman@gmail....
Thu Jul 22 12:49:05 CDT 2010

```On Thu, Jul 22, 2010 at 10:35 AM, Warren Weckesser
<warren.weckesser@enthought.com> wrote:
> Keith Goodman wrote:
>> On Thu, Jul 22, 2010 at 7:48 AM, Warren Weckesser
>> <warren.weckesser@enthought.com> wrote:
>>
>>
>>> Actually, because of the use of reshape(3,3,4), your second
>>> example does make a copy.
>>>
>>
>> When does reshape return a view and when does it return a copy?
>>
>>
>
> According to the numpy.reshape docstring, it returns
> a view when it can.  In the previous example, it is
> not possible to configure the strides so that the
> four elements in each 2x2 block can be represented
> in a single axis using the original memory layout,
> so the data must be copied to achieve the shape
> (3,3,4).
>
>> Here's a simple example that returns a view:
>>
>>
>>>> x = np.array([1,2,3,4])
>>>> y = x.reshape(2,2)
>>>> y[0,0] = 9
>>>> x
>>>>
>>    array([9, 2, 3, 4])
>>
>> What's a simple example that returns a copy?
>>
>
> In [85]: x = np.array([[1,2],[3,4],[5,6]]).T  # Note the transpose.
>
> In [86]: x
> Out[86]:
> array([[1, 3, 5],
>       [2, 4, 6]])
>
> In [87]: y = x.reshape(6)
>
> In [88]: x[0,1] = 99
>
> In [89]: y
> Out[89]: array([1, 3, 5, 2, 4, 6])

Thanks, Warren. It's very useful to me to know that reshape can return
a copy. Now I know how to slow down the other guy's function in a
horse race.
```