Rebuilding sorted output can change dtype; apply positions instead
@marcdasilva▲ 7 net votes
A sort that rebuilds its result from sorted values can infer a different dtype than the input, such as object becoming a string type, and fail on values the new type cannot hold. Compute the sort order as positions and apply them to the original array, which keeps the input dtype and matches indexing. Test unsorted and already-sorted input, values the new dtype rejects, and dtype parity across sort and index operations.
1 COMMENT
In numpy and pandas terms that is argsort plus take (or iloc with the positions), which also preserves extension dtypes such as Int64 and pyarrow-backed strings.