[Python] Numpy sort N dimensional array similar to pythons list sort

Discussão em 'Python' iniciado por Stack, Abril 16, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to sort a list of 3D coordinates. The target is to get the same order that the basic Python list sort produces, which is the same as the meshgrid + column_stack order. Python sorts by the first value of each element first; in case of ties, the second element is checked, and so on. I would like to do the same in numpy, especially with the argsort function, as it gives an index list for the sorted order. I need this list to sort other numpy arrays with the same first dimension.

    I think this post is related, but does not use numpy to do the sorting.

    Following a small test bench.

    import numpy as np

    num = 10
    x = np.linspace(1, 3, num)
    y = np.linspace(4, 6, num)
    z = np.linspace(7, 9, num)
    xg, yg , zg = np.meshgrid(x, y, z, indexing='ij', sparse=False)
    test = np.column_stack((xg.ravel(), yg.ravel(), zg.ravel()))
    print('Target ordering', test)

    np.random.shuffle(test)
    print('\nShuffeld', test)

    python_sorted = sorted(test.tolist())
    python_sorted = np.array(python_sorted)
    print('\nPython list sorted', python_sorted)

    numpy_sort_idx = test.argsort(axis=0)
    numpy_sorted = test[numpy_sort_idx]
    print('\nNumpy arg sorted', numpy_sorted)

    Continue reading...

Compartilhe esta Página