0

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.

7
  • Do you need to create a function to do this? Why not assign values directly by slicing without the function? Commented Dec 17, 2020 at 16:13
  • The reason is that my function is much more complicated than M[:,2] = 0 Commented Dec 17, 2020 at 16:16
  • Would passing both the list and array as inputs to the function work? Commented Dec 17, 2020 at 16:18
  • I do not understand the question - the function x operates on 2D Numpy array like in the example above Commented Dec 17, 2020 at 16:21
  • Is the list of numbers always consecutive numbers? Commented Dec 17, 2020 at 16:25

1 Answer 1

1

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]])
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the answer. I found that it is indeed not possible to make a slice from a list in general (e.g. scipy-cookbook.readthedocs.io/items/ViewsVsCopies.html). An alternative solution (and maybe preferable for me) is to rearrange the rows in A such that L would refer to consecutive sequence in the rearranged matrix.
@PavelProchazka no, AFAIK, even then A[:3][:2] might still give you a copy, and you can modify the original array.

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.