Home > Back-end >  How to find index that has same value in another array by python?
How to find index that has same value in another array by python?

Time:08-05

I'm a beginner of Python. I would like to find indexes that have two largest values in ndarray. For example, ndarray x like this.

x = np.array([2,3,5,3,7,3,1,5])

Because the two largest values are 7 and 5. The answer should be

ind = [2,4,7]
x[ind] = [5,7,5]

Would you tell me how to code it?

CodePudding user response:

You can accomplish this in 3 steps:

  1. Sort your unique array values (np.unique also sorts) np.unique(…)
  2. Slice the last N values (the maximums) from the sorted unique array …[-max_n:]
  3. Find the indices where your array has those maximums via np.where(np.isin(…))
import numpy as np

max_n = 2
x = np.array([2,3,5,3,7,3,1,5])
max_values = np.unique(x)[-max_n:]
max_indices = np.where(np.isin(x, max_values))[0]

print(
    f'{max_indices    = }',
    f'{x[max_indices] = }',
    sep='\n'
)
largest_indices    = array([2, 4, 7])
x[largest_indices] = array([5, 7, 5])

CodePudding user response:

You can use np.where selector. First you extract indices of the maximum value, then you work identically on a subset of the original array without this last value(s)

x = np.array([2,3,5,3,7,3,1,5])
largest_indices = np.where(x == np.max(x))[0]
# In one line you select the subarray without the largest value
largest2_indices = np.where(x == np.max(x[x < np.max(x)]))[0]
ind = np.sort(np.concatenate((largest_indices, largest2_indices)))

Or, in one single, confusing, line:

ind = np.sort(np.where((x == np.max(x)) | (x == np.max(x[x < np.max(x)])))[0])

The result:

print(ind)
>>> [2 4 7]
print(x[ind])
>>> [5 7 5]

CodePudding user response:

Theres several ways to accomplish this. One simple way is to

  1. Sort the array
sorted=np.argsort(x)

2.select the largest 2 values

max=x[-1]
second
for s in reversed(sorted):
   if s !=max:
     second=s
  1. Find the indexs with those values
  return np.where(x==max or x==second)
  • Related