如何根据两个条件从两个numpy数组中提取数据点?



我有两个numpy数组;x, y,我希望能够提取出x中最接近1且y值大于0.96的值,并获得该值的索引

x = [0.5, 0.8, 0.99, 0.8, 0.85, 0.9, 0.91, 1.01, 10, 20]
y = [0.7, 0.75, 0.8, 0.85, 0.9, 0.95, 0.99, 0.99, 0.99, 0.85]

在这种情况下,x值为1.01,因为它最接近1,y值为0.99。

理想的结果是:

idx = 7

我知道如何找到最接近1的点以及如何得到它的索引,但我不知道如何添加第二个条件。

当有多个索引满足条件时,此代码也适用。

import numpy as np
x = [0.5, 0.8, 0.99, 0.8, 0.85, 0.9, 0.91, 1.01, 10, 20]
y = [0.7, 0.75, 0.8, 0.85, 0.9, 0.95, 0.99, 0.99, 0.99, 0.85]
# differences
first_check = np.abs(np.array(x) - 1)
# extracting index of the value that x is closest to 1
# (indexes in case there are two or more values that are closest to 1)
indexes = np.where(first_check == np.min(first_check))[0]
indexes = [index for index in indexes if y[index] > 0.96]
print(indexes)

输出:

[7]

您可以使用np.argsort(abs(x - 1))根据最接近1的值对索引进行排序。然后,使用np.where抓取满足y > 0.96的第一个y索引。

import numpy as np
x = np.array([0.5, 0.8, 0.99, 0.8, 0.85, 0.9, 0.91, 1.01, 10, 20])
y = np.array([0.7, 0.75, 0.8, 0.85, 0.9, 0.95, 0.99, 0.99, 0.99, 0.85])
closest_inds = np.argsort(abs(x - 1))
idx = closest_inds[np.where(y[closest_inds] > 0.96)][0]

这将得到:

idx = 7

对于短数组(小于10k个元素),上面的解决方案会很慢,因为在numpy中没有findfirst。看看这个期待已久的功能请求。

因此,在这种情况下,下面的循环将更快,并将给出相同的结果:
for i in closest_inds:
if y[i] > 0.96:
idx = i
break 

这将在多个条件和列表中工作。

x = [0.5, 0.8, 0.99, 0.8, 0.85, 0.9, 0.91, 1.01, 10, 20]
y = [0.7, 0.75, 0.8, 0.85, 0.9, 0.95, 0.99, 0.99, 0.99, 0.85]

condition1 = 1.0
condition2 = 0.96

def convert(*args):
"""
Returns a list of tuples generated from multiple lists and tuples
"""
for x in args:
if not isinstance(x, list) and not isinstance(x, tuple):
return []
size = float("inf")

for x in args:
size = min(size, len(x)) 
result = []
for i in range(size):
result.append(tuple([x[i] for x in args]))
print(result)
return result
result = convert(x, y)
closest = min([tpl for tpl in result if tpl[0] >= condition1 and tpl[1] > condition2], key=lambda x: x[1])
index = result.index(closest)
print(f'The index of the closest numbers of x-list to 1 and y-list to 0.96 is {index}')

[(0.5, 0.7), (0.8, 0.75), (0.99, 0.8), (0.8, 0.85), (0.85, 0.9), (0.9, 0.95), (0.91, 0.99), (1.01, 0.99), (10, 0.99), (20, 0.85)]
The index of the closest numbers is 7

最新更新