如何检查Pandas数据帧的索引是否已排序

时间:2022-04-28 19:36:54

I have a vanilla pandas dataframe with an index. I need to check if the index is sorted. Preferably without sorting it again.

我有一个带有索引的香草熊猫数据框。我需要检查索引是否已排序。优选地,不再进行分类。

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()来测试索引以查看它是否是唯一的。是否有类似的方法来测试排序?

3 个解决方案

#1


37  

How about:

df.index.is_monotonic

#2


3  

If sort is all allowed, try

如果允许排序,请尝试

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

添加我刚发现的另一种方法。与第二个类似,但比较是有效的

all(df.index[:-1] <= df.index[1:]) 

#3


0  

For non-indices:

df.equals(df.sort())

#1


37  

How about:

df.index.is_monotonic

#2


3  

If sort is all allowed, try

如果允许排序,请尝试

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

添加我刚发现的另一种方法。与第二个类似,但比较是有效的

all(df.index[:-1] <= df.index[1:]) 

#3


0  

For non-indices:

df.equals(df.sort())