【问题标题】:numpy piecewise function claiming lists are not same sizenumpy分段函数声明列表的大小不同
【发布时间】:2013-05-02 19:20:38
【问题描述】:

我正在尝试编写一个函数来将变量传递给分段函数,我有:

def trans(a):
    np.piecewise(a, [(a<.05) & (a>=0),
                    (a<.1) & (a>= .05),
                    (a<.2) & (a>=.1),
                    (a<.4) & (a>=.2),
                    (a<1) & (a>=.4)],
                    [0,1,2,3,4])

但是,当我运行 trans(a) 时,我得到:

ValueError:函数列表和条件列表必须相同

我使用的函数和条件列表都是长度5,所以我不确定是什么问题

编辑:显然 numpy.piecewise 需要一个数组,所以我需要传递一个数组,而不是一个普通变量?

【问题讨论】:

    标签: python python-2.7 numpy scipy piecewise


    【解决方案1】:

    如果alist 而不是ndarray,这就是你得到的错误:

    >>> a = [1,2,7]
    >>> np.piecewise(a, [a == 1, a > 1, a > 4], [lambda x: 100*x, lambda x: x**2, lambda x: x])
    Traceback (most recent call last):
      File "<ipython-input-18-03e300b14962>", line 1, in <module>
        np.piecewise(a, [a == 1, a > 1, a > 4], [lambda x: 100*x, lambda x: x**2, lambda x: x])
      File "/usr/local/lib/python2.7/dist-packages/numpy/lib/function_base.py", line 693, in piecewise
        "function list and condition list must be the same")
    ValueError: function list and condition list must be the same
    
    >>> a = np.array(a)
    >>> np.piecewise(a, [a == 1, a > 1, a > 4], [lambda x: 100*x, lambda x: x**2, lambda x: x])
    array([100,   4,   7])
    

    发生这种情况是因为如果 a 是一个列表,那么向量比较的行为就不会像预期的那样:

    >>> a = [1,2,7]
    >>> [a == 1, a > 1, a > 4]
    [False, True, True]
    

    这些行在np.piecewise

    if isscalar(condlist) or \
           not (isinstance(condlist[0], list) or
                isinstance(condlist[0], ndarray)):
        condlist = [condlist]
    condlist = [asarray(c, dtype=bool) for c in condlist]
    

    意味着您最终会认为条件列表实际上看起来像

    [array([False,  True,  True], dtype=bool)]
    

    这是一个长度为 1 的列表。

    [哎呀——我刚刚注意到我的条件并不是相互排斥的。哦,好吧,反正解释是怎么回事也没关系。]

    【讨论】:

    • 感谢您解释这是为什么!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多