Naturally sorting Pandas DataFrame

Using sort_values for pandas >= 1.1.0 With the new key argument in DataFrame.sort_values, since pandas 1.1.0, we can directly sort a column without setting it as an index using natsort.natsort_keygen: df = pd.DataFrame({ “time”: [‘0hr’, ‘128hr’, ’72hr’, ’48hr’, ’96hr’], “value”: [10, 20, 30, 40, 50] }) time value 0 0hr 10 1 128hr 20 2 … Read more

Python analog of PHP’s natsort function (sort a list using a “natural order” algorithm) [duplicate]

From my answer to Natural Sorting algorithm: import re def natural_key(string_): “””See https://blog.codinghorror.com/sorting-for-humans-natural-sort-order/””” return [int(s) if s.isdigit() else s for s in re.split(r'(\d+)’, string_)] Example: >>> L = [‘image1.jpg’, ‘image15.jpg’, ‘image12.jpg’, ‘image3.jpg’] >>> sorted(L) [‘image1.jpg’, ‘image12.jpg’, ‘image15.jpg’, ‘image3.jpg’] >>> sorted(L, key=natural_key) [‘image1.jpg’, ‘image3.jpg’, ‘image12.jpg’, ‘image15.jpg’] To support Unicode strings, .isdecimal() should be used instead of … Read more