Skip to content Skip to sidebar Skip to footer

Valueerror From Simple Numpy Comparison

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

Solution 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.

Post a Comment for "Valueerror From Simple Numpy Comparison"