MarcoMag
MarcoMag

Reputation: 651

Can a slice of a numpy array be a view of another array?

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.        ])

Upvotes: 2

Views: 106

Answers (2)

user6655984
user6655984

Reputation:

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.

Upvotes: 2

Eric
Eric

Reputation: 97641

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

Upvotes: 1

Related Questions