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.        ])
1
  • In[16] copies values from b to a. It does not insert a link or reference to b. Commented Apr 18, 2017 at 16:09

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks ! This post provides additional information related to your answer link
Can't we write a[3:6] = b.view() instead?
You can write that. It won't do what you hope it to do, but you can write that.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.