1

I have an array A. I am printing a new array result by considering specific locations according to list J. However, I want to insert element 0 for all other positions. For example, I want to insert 0 at [0,2,3] locations of result since these are not included in J. I show the current and expected outputs.

import numpy as np
A=np.array([[1,2,3,4,5],
            [6,7,8,9,10],
            [11,12,13,14,15],
            [16,17,18,19,20],
            [21,22,23,24,25]])


J=[[1, 4]]
result=np.array([list(A[i]) for i in J[0]])
print([result])

The current output is

[array([[ 6,  7,  8,  9, 10],
       [21, 22, 23, 24, 25]])]

The expected output is

[array([[0, 0, 0, 0, 0],
        [ 6,  7,  8,  9, 10],
        [0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0],
        [21, 22, 23, 24, 25]])]
3
  • Your expected output is not a valid numpy array. All "columns" should have the same number of items. Commented Dec 29, 2022 at 14:10
  • I have corrected. Commented Dec 29, 2022 at 14:12
  • Ok, see answer below Commented Dec 29, 2022 at 14:18

1 Answer 1

2

You can use:

out = np.zeros_like(A)
out[J[0]] = A[J[0]]

Output:

array([[ 0,  0,  0,  0,  0],
       [ 6,  7,  8,  9, 10],
       [ 0,  0,  0,  0,  0],
       [ 0,  0,  0,  0,  0],
       [21, 22, 23, 24, 25]])

Or if you want to modify A in place:

A[~np.isin(np.arange(A.shape[0]), J[0])] = 0
Sign up to request clarification or add additional context in comments.

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.