有没有办法测试数据帧是否按照不是索引的给定列进行排序(即非索引列的等效于is_monotonic())而不重新调用排序,并且不转换列成一个索引?
答案 0 :(得分:16)
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"对于大多数用例,boolean应该是False
。 (对于涉及以整数表示的时间的情况,Pandas将其设置为True
。)返回值是一个元组,其第一个元素表示数组是否单调非递减,其第二个元素表示数组是否是单调非-increasing。其他元组元素依赖于版本:
>>> 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
所有这些函数都假设一个特定的输入dtype,甚至是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
我不完全确定为什么系列没有某种短路is_sorted
。可能有些东西比它看起来更棘手。
答案 1 :(得分:10)
您可以使用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
答案 2 :(得分:5)
同时,从0.19.0开始,有pandas.Series.is_monotonic_increasing
,pandas.Series.is_monotonic_decreasing
和pandas.Series.is_monotonic
。