2

I want to remove specific elements corresponding to certain indices of array inv_r. For example, I want to remove elements corresponding to indices (0,2),(1,0),(1,1) and obtain a flattened version as defined by T. The desired output is attached.

import numpy as np

inv_r=(1e4)*np.array([[0.60800941, 0.79907128, 0.99442121],
       [0.61174008, 0.84891968, 0.71449188],
       [0.6211801 , 0.88869614, 0.91835812]])

T=inv_r.flatten()
print([T])

The desired output is

[array([6080.0941, 7990.7128, 7144.9188,
       6211.801 , 8886.9614, 9183.5812])]
2
  • 1
    What about storing np.nan at those indexes, then flatten the array, while discaring nan values? Commented Jun 14, 2022 at 14:14
  • Or use a boolean mask that you can also flatten Commented Jun 14, 2022 at 14:15

1 Answer 1

2

You can use numpy.ravel_multi_index to convert your 2D indices into a flatten index, then delete them from T:

idx = [(0,2),(1,0),(1,1)]

drop = np.ravel_multi_index(np.array(idx).T, dims=inv_r.shape)
# array([2, 3, 4])

T = np.delete(inv_r.flatten(), drop)

output:

array([6080.0941, 7990.7128, 7144.9188, 6211.801 , 8886.9614, 9183.5812])
Sign up to request clarification or add additional context in comments.

2 Comments

How will the code change if idx=[]? The output should be array([6080.0941, 7990.7128, 9944.2121,6117.4008, 8489.1968,7144.9188, 6211.801 , 8886.9614, 9183.5812]).
You can maybe use an if here: if empty list -> flatten only

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.