问题
I want to modify the values of a sub-array in Python but it does not work the way I would like to. Here is an example, first let us consider the numpy arrays :
A = np.reshape(np.arange(25),(5,5))
and
B = np.ones((2,3))
If we check the values of A we get :
>>> A
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24]])
I want to replace in A the values of the sub-array
A[:,[1,3,4]][[1,3],:]
by the values of B. So what I am doing is the following :
A[:,[1,3,4]][[1,3],:] = B
and I would like to get :
>>> A
array([[ 0, 1, 2, 3, 4],
[ 5, 1, 7, 1, 1],
[10, 11, 12, 13, 14],
[15, 1, 17, 1, 1],
[20, 21, 22, 23, 24]])
But the values of A do not change with this method. Of course I could do it element by element with loops but the thing is that I want to do this with a 16000*16000 matrix so I am looking for a method that do not use loops. Can you please help me ?
Any help will be appreciated :)
回答1:
This is a confusing case. What's happening is
A[:, [1,3,4]]
indexes into A
, creating a new array containing columns 1, 3, and 4 of A
. The next expression, [[1, 3], :]
indexes the rows of that temporary array and sets it's values.
To work properly, you need to index columns and rows in the same expression. If you try that, however, it will raise an error
A[[1,3], [1,3,4]] = B ## Not working!
What's happening is that numpy interprets the lists as pairs of coordinates, which isn't what we want here (see https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html for details. It's essential reading if you want to get the most from numpy). Fortunately, numpy
provides the ix_
method for this case. It takes lists representing rows and columns and creates something that can be used as an index.
>>> A[np.ix_([1,3],[1,3,4])] = B
>>> A
array([[ 0, 1, 2, 3, 4],
[ 5, 1, 7, 1, 1],
[10, 11, 12, 13, 14],
[15, 1, 17, 1, 1],
[20, 21, 22, 23, -1]])
来源:https://stackoverflow.com/questions/53652185/modifying-values-of-a-sub-array-in-python