在pandas / numpy中实现分段函数的正确方法

时间:2018-02-04 02:37:12

标签: python pandas numpy scipy

我需要创建一个传递给curve_fit的函数。在我的例子中,函数最好定义为分段函数。

我知道以下内容不起作用,但我显示它,因为它使函数的意图明确:

def model_a(X, x1, x2, m1, b1, m2, b2):
    '''f(x) has form m1*x + b below x1, m2*x + b2 above x2, and is
    a cubic spline between those two points.'''
    y1 = m1 * X + b1
    y2 = m2 * X + b2
    if X <= x1:
        return y1    # function is linear below x1
    if X >= x2:
        return y2    # function is linear above x2
    # use a cubic spline to interpolate between lower
    # and upper line segment
    a, b, c, d = fit_cubic(x1, y1, x2, y2, m1, m2)
    return cubic(X, a, b, c, d)

当然,问题在于X是一个熊猫系列,形式(X <= x1)评估为一系列布尔值,所以这会失败并显示消息&#34;系列的真值是模棱两可的&#34;

np.piecewise()似乎是针对这种情况而设计的:&#34;无论condlist [i]为True,funclist [i](x)都用作输出值。&#34;所以我尝试了这个:

def model_b(X, x1, x2, m1, b1, m2, b2):
    def lo(x):
        return m1 * x + b1
    def hi(x):
        return m2 * x + b2
    def mid(x):
        y1 = m1 * x + b1
        y2 = m2 * x + b2
        a, b, c, d = fit_cubic(x1, y1, x2, y2, m1, m2)
        return a * x * x * x + b * x * x + c * x + d

    return np.piecewise(X, [X<=x1, X>=x2], [lo, hi, mid])

但是这次会议失败了:

return np.piecewise(X, [X<=x1, X>=x2], [lo, hi, mid])

带有消息&#34; IndexError:数组&#34;的索引太多了。我倾向于认为它反对 condlist 中有两个元素和 funclist 中的三个元素这一事实,但文档明确指出 funclist 中的额外元素被视为默认元素。

任何指导?

1 个答案:

答案 0 :(得分:5)

NumPy对np.piecewise的定义piece of codelist / ndarray - 以中心为准:

# undocumented: single condition is promoted to a list of one condition
if isscalar(condlist) or (
        not isinstance(condlist[0], (list, ndarray)) and x.ndim != 0):
    condlist = [condlist]

因此,如果X是系列,则condlist = [X<=x1, X>=x2]是两个Series的列表。 由于condlist[0]既不是list也不是ndarraycondlist被“提升”为一个条件的列表:

condlist = [condlist]

由于这不是我们想要发生的事情,我们需要在将condlist传递给np.piecewise之前将X = X.values 列为NumPy数组:

import numpy as np
import pandas as pd
def model_b(X, x1, x2, m1, b1, m2, b2):
    def lo(x):
        return m1 * x + b1
    def hi(x):
        return m2 * x + b2
    def mid(x):
        y1 = m1 * x + b1
        y2 = m2 * x + b2
        # a, b, c, d = fit_cubic(x1, y1, x2, y2, m1, m2)
        a, b, c, d = 1, 2, 3, 4
        return a * x * x * x + b * x * x + c * x + d
    X = X.values
    return np.piecewise(X, [X<=x1, X>=x2], [lo, hi, mid])

X = pd.Series(np.linspace(0, 100, 100))
x1, x2, m1, b1, m2, b2 = 30, 60, 10, 5, -20, 30
f = model_b(X, x1, x2, m1, b1, m2, b2)

例如,

{{1}}