2024-05-13 09:27:44 发布
网友
我可以使用is_单调方法检查pandas.DataFrame()的索引是否单调递增。但是,我想检查一个列的值是否严格地增加了值(float/integer)?
In [13]: my_df = pd.DataFrame([1,2,3,5,7,6,9]) In [14]: my_df Out[14]: 0 0 1 1 2 2 3 3 5 4 7 5 6 6 9 In [15]: my_df.index.is_monotonic Out[15]: True
Pandas 0.19添加了一个公共的^{}API(以前,这只在未记录的algos模块中可用)。
algos
(已更新)请注意,尽管有其名称,Series.is_monotonic仅指示序列是否单调地递增(相当于使用Series.is_monotonic_increasing)。相反,使用Series.is_monotonic_decreasing。 无论如何,两者都是非严格的,但是您可以将它们与^{}组合以获得严格性。
Series.is_monotonic
Series.is_monotonic_increasing
Series.is_monotonic_decreasing
例如:
my_df = pd.DataFrame([1,2,2,3], columns = ['A']) my_df['A'].is_monotonic # non-strict Out[1]: True my_df['A'].is_monotonic_increasing # equivalent to is_monotonic Out[2]: True (my_df['A'].is_monotonic_increasing and my_df['A'].is_unique) # strict Out[3]: False my_df['A'].is_monotonic_decreasing # Other direction (also non-strict) Out[4]: False
您可以使用apply在数据帧级别运行它:
apply
my_df = pd.DataFrame({'A':[1,2,3],'B':[1,1,1],'C':[3,2,1]}) my_df Out[32]: A B C 0 1 1 3 1 2 1 2 2 3 1 1 my_df.apply(lambda x: x.is_monotonic) Out[33]: A True B True C False dtype: bool
如果两个指数相等,它们就不是唯一的。所以你可以使用:
my_df.Index.is_monotonic and my_df.Index.is_unique
这些属性记录在版本15.2中;is_unique在14.1中略述过,但对我来说很有用。见
http://pandas.pydata.org/pandas-docs/version/0.15.2/api.html#indexhttp://pandas.pydata.org/pandas-docs/version/0.14.1/generated/pandas.Index.html
最好的方法可能是将dataframe列作为numpy数组获取,而不必四处复制数据(在通过索引选择列之后使用the ^{} property),然后使用基于numpy的测试检查单调性:
def monotonic(x): return np.all(np.diff(x) > 0) monotonic(df[0].values)
纯Python实现,从这里借用:Python - How to check list monotonicity
def strictly_increasing(L): return all(x<y for x, y in zip(L, L[1:]))
Pandas 0.19添加了一个公共的^{} API(以前,这只在未记录的
algos
模块中可用)。(已更新)请注意,尽管有其名称,} 组合以获得严格性。
Series.is_monotonic
仅指示序列是否单调地递增(相当于使用Series.is_monotonic_increasing
)。相反,使用Series.is_monotonic_decreasing
。 无论如何,两者都是非严格的,但是您可以将它们与^{例如:
您可以使用
apply
在数据帧级别运行它:如果两个指数相等,它们就不是唯一的。所以你可以使用:
这些属性记录在版本15.2中;is_unique在14.1中略述过,但对我来说很有用。见
http://pandas.pydata.org/pandas-docs/version/0.15.2/api.html#indexhttp://pandas.pydata.org/pandas-docs/version/0.14.1/generated/pandas.Index.html
最好的方法可能是将dataframe列作为numpy数组获取,而不必四处复制数据(在通过索引选择列之后使用the ^{} property ),然后使用基于numpy的测试检查单调性:
纯Python实现,从这里借用:Python - How to check list monotonicity
相关问题 更多 >
编程相关推荐