如何检查 Pandas 数据框的索引是否已排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17315881/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I check if a Pandas dataframe's index is sorted
提问by Pablojim
I have a vanilla pandas dataframe with an index. I need to check if the index is sorted. Preferably without sorting it again.
我有一个带有索引的 vanilla pandas 数据框。我需要检查索引是否已排序。最好不要再次排序。
e.g. I can test an index to see if it is unique by index.is_unique() is there a similar way for testing sorted?
例如,我可以通过 index.is_unique() 测试索引以查看它是否唯一是否有类似的测试排序方法?
回答by Wes McKinney
How about:
怎么样:
df.index.is_monotonic
df.index.is_monotonic
回答by waitingkuo
If sortis all allowed, try
如果sort全部允许,请尝试
all(df.sort_index().index == df.index)
If not, try
如果没有,请尝试
all(a <= b for a, b in zip(df.index, df.index[1:]))
The first one is more readable while the second one has smaller time complexity.
第一个更具可读性,而第二个具有较小的时间复杂度。
EDIT
编辑
Add another method I've just found. Similar with the second one but the comparison is vetorized
添加我刚刚发现的另一种方法。与第二个相似,但比较是 vetorized
all(df.index[:-1] <= df.index[1:])
回答by nick_eu
For non-indices:
对于非指数:
df.equals(df.sort())

