Python 有没有更简单的方法来制作一个单调的熊猫系列?

Python 有没有更简单的方法来制作一个单调的熊猫系列?,python,pandas,numpy,Python,Pandas,Numpy,我正在寻找一种快速的方法,使熊猫数据帧在x中单调 我目前的解决方案如下: def make_monotonic(df, cols=None): """make df monotonic""" if not cols: cols = df.columns mycol = "_maximum" dfm = df.copy() for col in cols: dfm[mycol] = np.maximum.accumulat

我正在寻找一种快速的方法,使熊猫数据帧在x中单调

我目前的解决方案如下:

def make_monotonic(df, cols=None):
    """make df monotonic"""
    if not cols:
        cols = df.columns

    mycol = "_maximum"

    dfm = df.copy()
    for col in cols:
        dfm[mycol] = np.maximum.accumulate(dfm[col])
        dfm.drop_duplicates([mycol], keep="first", inplace=True)
    del dfm[mycol]
    return dfm

n=21
np.random.seed(21)
x = np.linspace(0,np.pi,n)
dx = .5 * (np.random.random(n)-.5)
df = pd.DataFrame.from_dict({"x0":x, "x":x+dx, "y":np.sin(x)})
dfm = make_monotonic(df, cols=["x"])

我想生成一个函数y=f(x)


使用
df.cummax()
实际上有一种非常简单的方法来实现这一点

旧逻辑如下:

您可以继续使用
diff
方法获取行中的差异,直到所有值都大于0

while True:
    mon_inc = df['x'].diff().fillna(0) >= 0
    if mon_inc.all():
        break
    df = df[mon_inc]
和一个函数,用于执行任意数量的列

def make_monotonic(df, cols=None):
    if cols is None:
        cols = df.columns

    df1 = df.copy()[cols]

    while True:
        mon_inc = (df1.diff().fillna(0) >= 0).all(axis=1)
        if mon_inc.all():
            break
        df1 = df1[mon_inc]
    return df1

一个系列在文字上是单调的,这意味着什么呢?“x中的单调”意味着每行中的x值应始终大于前一行中的x值。那么你的意思是只对数据进行排序?不,数据帧已经排序(索引!)。我将跳过那些破坏单调的行。我只需要递增
x
值,例如使用
np.interp
中的列。感谢您的快速回答。解决方案看起来不错。循环的数量对于我的用例来说并不多。哇!惊人;-)(对自己说:RTFM…)不幸的是,由于分数不够,我不能投你的票,但我稍后会回来;-)
cols = ['your', 'columns']
mon_inc = (df[cols].cummax().diff().fillna(.1) > 0).all(axis=1)
df[mon_inc]
while True:
    mon_inc = df['x'].diff().fillna(0) >= 0
    if mon_inc.all():
        break
    df = df[mon_inc]
def make_monotonic(df, cols=None):
    if cols is None:
        cols = df.columns

    df1 = df.copy()[cols]

    while True:
        mon_inc = (df1.diff().fillna(0) >= 0).all(axis=1)
        if mon_inc.all():
            break
        df1 = df1[mon_inc]
    return df1