找到你要的答案

Q:ValueError from simple Numpy comparison [duplicate]

Q:从简单的NumPy比较[复制] ValueError

I encountered a python issue, I tried various ways but I could not fix it. Would you offer me some hint?

sp_step = np.linspace(0.0,2.0,41)  ####  bin size is 50 Kpc
for jj in range(len(sp_step) -1):
    if sp > sp_step[jj] and sp <= sp_step[jj+1]:
        stack_num[jj] += 1
        stack[jj] = map(add,stack[jj],flux_inteplt)

I define a numpy array called sp_step, what I want to do is use the variable sp to find which segment of the data is in, then I will stack the corresponding data.

But it says

if sp > sp_step[jj] and sp <= sp_step[jj+1]:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

I googled this error, tried np.logical_and, but not work.

Thanks.

我遇到了一个Python的问题,我想尽各种办法,但我无法修复。你能给我一些提示吗?

sp_step = np.linspace(0.0,2.0,41)  ####  bin size is 50 Kpc
for jj in range(len(sp_step) -1):
    if sp > sp_step[jj] and sp <= sp_step[jj+1]:
        stack_num[jj] += 1
        stack[jj] = map(add,stack[jj],flux_inteplt)

我定义了一个称为sp_step NumPy数组,我想要做的是使用可变SP找到数据段,然后将堆栈对应的数据。

但是它说

if sp > sp_step[jj] and sp <= sp_step[jj+1]:

ValueError:一个具有多个元素的数组的值是模糊的。使用A或A all() any()

我想这个错误,试图np.logical_and,但不工作。

谢谢.

answer1: 回答1:

This is one of the more common SO numpy questions. It's the result of some numpy test producing multiple values, and then trying to use that in a Python context that expects only one value.

Take a look at this expression (print its result)

sp > sp_step[jj] and sp <= sp_step[jj+1]

You may need to add some () to ensure that both equality tests are performed before the & (and is Python's operator that expects scalar booleans).

(sp > sp_step[jj]) & (sp <= sp_step[jj+1])

To be used with if it has to return just one value.

It is best, when testing numpy arrays, to use a mask rather than iteration.

mask = (sp>sp_step) & (sp <= sp_step)
sp_step[mask] ...

Generally it is faster than iterations, but it can require rethinking the problem. In any case, the ValueError is the result of mixing multiple valued numpy logical operations with scalar Python ones.

这是一个比较常见的问题所以NumPy。这是一些NumPy生产试验多元价值的结果,然后尝试使用在Python的背景下,预计只有一个值。

看看这个表达式(打印它的结果)

sp > sp_step[jj] and sp <= sp_step[jj+1]

你可能需要添加一些()来确保平等试验前及执行;(是Python的运营商,预计标量布尔)。

(sp > sp_step[jj]) & (sp <= sp_step[jj+1])

如果它只返回一个值,则使用。

这是最好的,当测试NumPy数组,使用面膜而不是迭代。

mask = (sp>sp_step) & (sp <= sp_step)
sp_step[mask] ...

一般来说,它比迭代快,但它需要重新思考这个问题。在任何情况下,该ValueError是混合多值逻辑运算与Python的NumPy标量结果。

python  numpy