Reputation: 4525
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
?
Upvotes: 2
Views: 79
Reputation: 67437
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
Upvotes: 2
Reputation: 7842
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]])
Upvotes: 2