[Python] Difference between np.argsort and index_natsorted natural sort

Discussão em 'Python' iniciado por Stack, Outubro 4, 2024.

  1. Stack

    Stack Membro Participativo

    I have the below dataframe and I want to sort naturally by 'time' column.

    df = pd.DataFrame({
    "time": ['0hr', '128hr', '72hr', '48hr', '96hr'],
    "value": [10, 20, 30, 40, 50]
    })

    df.sort_values(
    by="time",
    key=lambda x: index_natsorted(df["time"])

    )


    I use the natsort.index_natsorted function which is supposed to return the 'time' column in the sequence of ['0hr','48hr','72hr','96hr','128hr'], because the index_natsorted, applied to the given 'time' column, returns a tuple of [0, 3, 2, 4, 1], which suppose to sort the column in the above manner, with 0 in tuple referring to the first element '0hr' of the 'time' column, and the subsequent 3 in tuple referring to the fourth element '48hr' of the 'time' column, and so on...

    However the output I got is:

    output:
    time value
    0hr 10
    96hr 50
    72hr 30
    128hr 20
    48hr 40



    Could someone explain to me why the index_natsorted function will return the 'time' column in this sequence?

    Similar to np.argsort, the docs of index_natsorted reads that it " Sorts a sequence naturally, but returns a list of sorted the indexes and not the sorted list itself." So I am curious as to why in this case its returned indices will not sort the elements naturally.

    Continue reading...

Compartilhe esta Página