[Python] Query an array where two other arrays align

Discussão em 'Python' iniciado por Stack, Maio 3, 2025.

  1. Stack

    Stack Membro Participativo

    I have 3 arrays, x, y, and q. Arrays x and y have the same length, q is a query array. Assume all values in x and q are unique. For each value of q, I would like to find the index of the corresponding value in x. I would then like to query that index in y. If a value from q does not appear in x, I would like to return np.nan.

    As a concrete example, consider the following arrays:

    x = np.array([1, 2, 3])
    y = np.array([4, 5, 6])
    q = np.array([2, 0])


    Since only the value 2 occurs in x, the correct return value would be:

    out = np.array([5, np.nan])


    With for loops, this can be done like so:

    out = []
    for i in range(len(q)):
    for j in range(len(x)):
    if np.allclose(q, x[j]):
    out.append(y[j])
    break
    else:
    out.append(np.nan)
    output = np.array(out)


    Obviously this is quite slow. Is there a simpler way to do this with numpy builtins like np.argwhere? Or would it be easier to use pandas?

    Continue reading...

Compartilhe esta Página