sort by the column of “nl10107” and obtain the sort order in python

Assuming you have a pandas dataframe called df, and you want to sort by the column "nl10107", you can use the sort_values function from pandas library with parameter "by" set to the desired column name. Then you can use the resulting dataframe's index to obtain the sort order. Here's an example:

main.py
import pandas as pd

# create a sample dataframe
df = pd.DataFrame({'col1': [1, 2, 3], 'nl10107': [4, 2, 1], 'col3': [2, 1, 3]})

# sort by column nl10107
sorted_df = df.sort_values(by='nl10107')

# print sorted dataframe
print(sorted_df)

# get the sort order
sort_order = sorted_df.index.values

# print sort order
print(sort_order)
335 chars
17 lines

The output will be:

main.py
   col1  nl10107  col3
2     3        1     3
1     2        2     1
0     1        4     2

[2 1 0]
101 chars
7 lines

The sort_order variable contains the index values of the sorted dataframe, which represents the sort order.

related categories

gistlibby LogSnag