查找一个序列大于另一个序列的索引

时间:2013-03-22 17:02:28

标签: python numpy

我有两个numpy数组,我想找到一个数组中的数据变得比另一个数组大的索引。以下代码似乎可以解决这个问题,但我想知道是否有更好的方法:

# For example
import numpy as np

x=np.arange(-10,10,0.01)
f1 = x+3.0
f2 = 2*x

cross_over_index = np.nonzero(f2 > f1)[0][0]

2 个答案:

答案 0 :(得分:0)

因为你的问题只有在数组被排序时才有意义,你可以找到带有二进制搜索的交叉点,这对于大型数组来说要快得多:

# Find first index of a2 > a1
def crossover(a1, a2):
    bottom = 0
    top = min(len(a1) - 1, len(a2) - 1)

    if a2[top] <= a1[top]:
        return -1

    while top > bottom:
        mid = (top + bottom) >> 1
        if a2[mid] > a1[mid]:
            top = mid
        else:
            bottom = mid + 1
    return top

f1 = [ (x + 20) for x in range(80) ]
f2 = [ (2 * x) for x in range(100) ]

print( crossover( f1, f2 ) )

这应该(并且确实)打印&#34; 21&#34;。

答案 1 :(得分:0)

如果您正在寻找等式的解 f 1 (x)= f 2 (x),您还可以这样做:

np.argmin(abs(f2-f1))
# 1300

并在那里获得x

x[np.argmin(abs(f2-f1))]
# 3.0

但请注意,这有时只会给出与您的技术要求相同的答案(在此示例中返回i0 --> 1301x0 --> 3.01(这是x的解决方案加上步骤)。