Home > Mobile >  Removing specific elements from an array in Python
Removing specific elements from an array in Python

Time:06-15

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])]

CodePudding user response:

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])
  • Related