2
a = [3,4,5,6]
b = [1,2,3]
adj = np.random.rand(10,10)
adj[a,:][:,b] = adj[a,:][:,b]  + 1000 

Why do the element values of adj not change after adj[a,:][:,b] = adj[a,:][:,b] + 1000?

6
  • Numpy is probably unable to get a view of that slice, so you end up with a copy. Modifying the copy does noe update the original Commented Mar 27, 2014 at 8:55
  • is there any way to modify the value using indexing? Commented Mar 27, 2014 at 8:55
  • If it's not performance critical, use a for loop,like for bi in b: adj[a,bi]+=1000. Commented Mar 27, 2014 at 8:58
  • I am curious why it does not change the value Commented Mar 27, 2014 at 9:00
  • 2
    @Sean Indexing multidimensional arrays always returns a copy. docs.scipy.org/doc/numpy/user/… Commented Mar 27, 2014 at 9:03

2 Answers 2

2

As has been pointed out, fancy indexing always returns a copy, not a slice. So you are modifying a copy that is later discarded.

When indexing several dimensions with arrays, this get broadcasted to a common shape, so any of the following will also do the trick for you:

a = [[3], [4], [5], [6]]
b = [1, 2, 3]
adj[a, b] += 1000

a = np.array([3, 4, 5, 6]
b = [1, 2, 3]
adj[a[:, None], b] += 1000

And of course, what should be your first option for your actual indices, although it will not work if they are not all consecutive integers:

adj[3:7, 1:4] += 1000
Sign up to request clarification or add additional context in comments.

Comments

2

So I suspect numpy can't return a view to that slice, so you are trying to modify a copy that gets garbage collected.

A solution is to use meshgrid. For example:

a = [3,4,5,6]
b = [1,2,3] 
adj = np.arange(7*7).reshape(7,7)
X,Y = np.meshgrid(a,b)
x,y = X.ravel(),Y.ravel()
adj[(x,y)]+=1000

Where adj is now:

array([[   0,    1,    2,    3,    4,    5,    6],
       [   7,    8,    9,   10,   11,   12,   13],
       [  14,   15,   16,   17,   18,   19,   20],
       [  21, 1022, 1023, 1024,   25,   26,   27],
       [  28, 1029, 1030, 1031,   32,   33,   34],
       [  35, 1036, 1037, 1038,   39,   40,   41],
       [  42, 1043, 1044, 1045,   46,   47,   48]])

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.