将 Pandas 系列转换为单调 [英] Transform a Pandas series to be monotonic

查看:63
本文介绍了将 Pandas 系列转换为单调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方法来消除破坏系列单调性的点.

例如

s = pd.Series([0,1,2,3,10,4,5,6])

s = pd.Series([0,1,2,3,-1,4,5,6])

我们会提取

s = pd.Series([0,1,2,3,4,5,6])

<块引用>

注意:我们假设第一个元素总是正确的.

解决方案

Monotonic 可以是递增的也可以是递减的,下面的函数将返回排除所有具有单调性的值.

但是,鉴于系列 s = pd.Series([0,1,2,3,10,4,5,6]),您的问题似乎有些混乱,10 不会破坏单调性条件,4, 5, 6 会.所以正确答案是 0, 1, 2, 3, 10

将pandas导入为pds = pd.Series([0,1,2,3,10,4,5,6])def to_monotonic_inc(s):返回 s[s >= s.cummax()]def to_monotonic_dec(s):返回 s[s <= s.cummin()]打印(to_monotonic_inc(s))打印(to_monotonic_dec(s))

输出为 0, 1, 2, 3, 10 增加和 0 减少.

也许您想找到最长单调数组?因为那是一个完全不同的搜索问题.

----- 编辑 -----

下面是一个简单的方法来找到最长单调递增数组给你的使用普通python的约束:

def get_longeset_monotonic_asc(s):enumerated = sorted([(v, i) for i, v in enumerate(s) if v >= s[0]])[1:]输出 = [s[0]]最后索引 = 0对于 v, i 在枚举中:如果我>last_index:last_index = 我output.append(v)返回输出s1 = [0,1,2,3,10,4,5,6]s2 = [0,1,2,3,-1,4,5,6]打印(get_longeset_monotonic_asc(s1))打印(get_longeset_monotonic_asc(s2))'''输出:[0, 1, 2, 3, 4, 5, 6][0, 1, 2, 3, 4, 5, 6]'''

请注意,此解决方案涉及的排序是 O(nlog(n)) + 第二个步骤 O(n).

I'm looking for a way to remove the points that ruin the monotonicity of a series.

For example

s = pd.Series([0,1,2,3,10,4,5,6])

or

s = pd.Series([0,1,2,3,-1,4,5,6])

we would extract

s = pd.Series([0,1,2,3,4,5,6])

NB: we assume that the first element is always correct.

解决方案

Monotonic could be both increasing or decreasing, the functions below will return exclude all values that brean monotonicity.

However, there seems to be a confusion in your question, given the series s = pd.Series([0,1,2,3,10,4,5,6]), 10 doesn't break monotonicity conditions, 4, 5, 6 do. So the correct answer there is 0, 1, 2, 3, 10

import pandas as pd

s = pd.Series([0,1,2,3,10,4,5,6])

def to_monotonic_inc(s):
    return s[s >= s.cummax()]

def to_monotonic_dec(s):
    return s[s <= s.cummin()]

print(to_monotonic_inc(s))
print(to_monotonic_dec(s))

Output is 0, 1, 2, 3, 10 for increasing and 0 for decreasing.

Perhaps you want to find the longest monotonic array? because that's a completely different search problem.

----- EDIT -----

Below is a simple way of finding the longest monotonic ascending array given your constraints using plain python:

def get_longeset_monotonic_asc(s):
    enumerated = sorted([(v, i) for i, v in enumerate(s) if v >= s[0]])[1:]
    output = [s[0]]
    last_index = 0
    for v, i in enumerated:
        if i > last_index:
            last_index = i
            output.append(v)

    return output

s1 = [0,1,2,3,10,4,5,6]
s2 = [0,1,2,3,-1,4,5,6]

print(get_longeset_monotonic_asc(s1))
print(get_longeset_monotonic_asc(s2))

'''
Output:

[0, 1, 2, 3, 4, 5, 6]
[0, 1, 2, 3, 4, 5, 6]

'''

Note that this solution involves sorting which is O(nlog(n)) + a second step which is O(n).

这篇关于将 Pandas 系列转换为单调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆