This may seem like a duplicate of Check whether non-index column sorted in Pandas
I read that post and all the answers. No one (save one answer) addresses using numpy. It's all focused on python lists. By asking a similar question with the numpy
tag, I believe I'll get a different class of answers. That said, on to the question.
consider two arrays a
and b
. b
is sorted while a
is not.
a = np.array([2, 1, 3, 0])
b = np.arange(4)
I've written this function to determine sorted-ness
def is_sorted(x):
return (np.arange(len(x)) == np.argsort(x)).all()
What else can I do to improve on this idea? What is the quickest pandas
or numpy
algorithm to determine if a pd.Series
or np.ndarray
is sorted?
is_sorted(a)
False
is_sorted(b)
True
it is O(nlogn) to sort an array, but to tell if an array is already sorted it only takes O(n).
is_sorted = lambda x: (np.diff(x)>=0).all()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With