2

I'm trying to write a function to pass a variable into a piecewise function, I have:

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])

However, when I run trans(a), I get:

ValueError: function list and condition list must be the same

The function and condition list I used are both length 5, so I'm not sure what the issue is

EDIT: Apparently numpy.piecewise expects an array, so I needed to pass it one, instead of a plain variable?

4

1 回答 1

3

a如果是 alist而不是a ,这就是你会得到的错误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 的列表。

[糟糕——我只是注意到我的条件并不是相互排斥的。哦,好吧,无论如何解释发生了什么都没关系。]

于 2013-05-02T19:40:34.857 回答