检查非索引列是否在 Pandas 中排序

Check whether non-index column sorted in Pandas

有没有一种方法可以测试数据帧是否按给定的不是索引的列排序(即,对于非索引列,是否有等同于 is_monotonic() 的方法),而无需全面调用排序再次,并且不将列转换为索引?

可以使用numpy的方法:

import numpy as np

def is_df_sorted(df, colname):
    return (np.diff(df[colname]) > 0).all()

更直接的方法(就像你建议的那样,但你说你不想要它..)是转换为索引并使用 is_monotonic 属性:

import pandas as pd

def is_df_sorted(df, colname):
    return pd.Index(df[colname]).is_monotonic

pd.algos 中有一些函数可能有用。它们都是未记录的实现细节,因此它们可能会因版本而异:

>>> pd.algos.is[TAB]
pd.algos.is_lexsorted          pd.algos.is_monotonic_float64  pd.algos.is_monotonic_object
pd.algos.is_monotonic_bool     pd.algos.is_monotonic_int32
pd.algos.is_monotonic_float32  pd.algos.is_monotonic_int64    

is_monotonic_* 函数采用指定 dtype 的数组和一个 "timelike" 布尔值,对于大多数用例来说应该是 False。 (对于涉及以整数表示的时间的情况,Pandas 将其设置为 True。)return 值是一个元组,其第一个元素表示数组是否单调非递减,第二个元素表示element 表示数组是否单调非递增。其他元组元素与版本相关:

>>> df = pd.DataFrame({"A": [1,2,2], "B": [2,3,1]})
>>> pd.algos.is_monotonic_int64(df.A.values, False)[0]
True
>>> pd.algos.is_monotonic_int64(df.B.values, False)[0]
False

所有这些函数都假定一个特定的输入数据类型,甚至 is_lexsorted,它假定输入是一个 int64 数组的列表。传递错误的 dtype,它真的很困惑:

In [32]: pandas.algos.is_lexsorted([np.array([-2, -1], dtype=np.int64)])
Out[32]: True
In [33]: pandas.algos.is_lexsorted([np.array([-2, -1], dtype=float)])
Out[33]: False
In [34]: pandas.algos.is_lexsorted([np.array([-1, -2, 0], dtype=float)])
Out[34]: True

我不完全确定为什么 Series 还没有某种短路 is_sorted。可能有些事情让它比看起来更棘手。

同时,从 0.19.0 开始,有 pandas.Series.is_monotonic_increasingpandas.Series.is_monotonic_decreasingpandas.Series.is_monotonic