[英]How to find index that has same value in another array by python?
I'm a beginner of Python.我是 Python 的初学者。 I would like to find indexes that have two largest values in ndarray.
我想在 ndarray 中找到具有两个最大值的索引。 For example, ndarray x like this.
例如,ndarray x 像这样。
x = np.array([2,3,5,3,7,3,1,5])
Because the two largest values are 7 and 5. The answer should be因为两个最大值是 7 和 5。答案应该是
ind = [2,4,7]
x[ind] = [5,7,5]
Would you tell me how to code it?你能告诉我如何编码吗?
You can accomplish this in 3 steps:您可以通过 3 个步骤完成此操作:
np.unique(…)
np.unique(…)
…[-max_n:]
…[-max_n:]
np.where(np.isin(…))
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])
You can use np.where
selector.您可以使用
np.where
选择器。 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]
Theres several ways to accomplish this.有几种方法可以做到这一点。 One simple way is to
一种简单的方法是
sorted=np.argsort(x)
2.select the largest 2 values 2.select最大2个值
max=x[-1]
second
for s in reversed(sorted):
if s !=max:
second=s
return np.where(x==max or x==second)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.