[Python] Fastest way of creating a pair-wise matching matrix from a single numpy array

Discussão em 'Python' iniciado por Stack, Junho 30, 2025.

  1. Stack

    Stack Membro Participativo

    I want to do quick pair-wise matchings of all elements in a numpy array, ignoring self-matching.

    For example given a numpy array like

    a = np.array(range(4))


    I want to get a matrix like

    array([[0, 1],
    [0, 2],
    [0, 3],
    [1, 0],
    [1, 2],
    [1, 3],
    [2, 0],
    [2, 1],
    [2, 3],
    [3, 0],
    [3, 1],
    [3, 2]])


    In my real case, I have different sizes of arrays varying from 1 to 1000. I need to constantly call a function that does this pair-wise matching. I wrote the code below

    import numpy as np
    from itertools import permutations

    a = np.array(range(1000))
    xs, ys = zip(*[(x, y) for x, y in permutations(a, 2)])
    res = np.vstack([np.array(xs), np.array(ys)]).T
    print(res)


    I want to know if there are faster ways (maybe more numpyic ways) to do this?

    I would like to see some benchmarkings of runtime vs. array size.

    Continue reading...

Compartilhe esta Página