Reputation: 771
Consider 2D Numpy array A
and in-place function x
like
A = np.arange(9).reshape(3,3)
def x(M):
M[:,2] = 0
Now, I have a list (or 1D numpy array) L
pointing the rows, I want to select and apply the function f
on them like
L = [0, 1]
x(A[L, :])
where the output will be written to A. Since I used index access to A, the matrix A is not affected at all:
A = array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
What I actually need is to slice the matrix such as
x(A[:2, :])
giving me the desired output
A = array([[0, 1, 0],
[3, 4, 0],
[6, 7, 8]])
The question is now, how to provide Numpy array slicing by the list L
(either any automatic conversion of list to slice or if there is any build in function for that), because I am not able to convert the list L
easily to slice like :2
in this case.
Note that I have both large matrix A
and list L
in my problem - that is the reason, why I would need the in-place operations to control the available memory.
Upvotes: 0
Views: 158
Reputation: 150735
Can you modify the function so as you can pass slice L
inside it:
def func(M,L):
M[L,2] = 0
func(A,L)
print(A)
Out:
array([[0, 1, 0],
[3, 4, 0],
[6, 7, 8]])
Upvotes: 1