2

I might have used the wrong terminology for this question, consequently there might have been a replicate of this question, but I was not able to find it.

In the following example, if it is possible, what would be the instruction in In [16] such that if b is modified, the slice of a a[3:6] is affected too ?

In [12]: import numpy as np

In [13]: a = np.zeros((7))

In [14]: b = np.random.rand(3,)

In [15]: b
Out[15]: array([ 0.76954692,  0.74704679,  0.05969099])

In [16]: a[3:6] = b

In [17]: b[0] = 2.2

In [18]: a # a has not changed
Out[18]:
array([ 0.        ,  0.        ,  0.        ,  0.76954692,  0.74704679,
        0.05969099,  0.        ])
MarcoMag
  • 556
  • 7
  • 18

2 Answers2

2

After the assignment a[3:6] = b, add the line b = a[3:6]. Then b becomes a view into the array a, and so a modification of b will modify a accordingly. (And the other way around).

A numeric NumPy array contains numbers (of the same dtype), not references or any other kinds of structure. The entire array may be a view of another array (in which case it uses its data instead of having its own), but a part of it cannot. Assignment to a slice always copies data.

  • Thanks ! This post provides additional information related to your answer [link](http://stackoverflow.com/questions/4370745/view-onto-a-numpy-array#4371049) – MarcoMag Apr 19 '17 at 05:46
  • Can't we write `a[3:6] = b.view()` instead? – MarcoMag Apr 25 '17 at 06:43
  • You can write that. It won't do what you hope it to do, but you can write that. –  Apr 25 '17 at 14:21
1

Another way to write this:

a = np.zeros((7))
b = a[3:6]  # b is now a view to a

b[:] = np.random.rand(3)  # changes both b and a
                          # the [:] is so we don't create a new variable
Eric
  • 95,302
  • 53
  • 242
  • 374