0

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.

msw
  • 42,753
  • 9
  • 87
  • 112
Huanian Zhang
  • 830
  • 3
  • 16
  • 37

1 Answers1

3

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.

hpaulj
  • 221,503
  • 14
  • 230
  • 353
  • Sorry to duplicate close this on you, but you did gain a few upvotes while I was looking. Yes, it is a frequently asked question and frequently answered by you. I wish I could find a canonical Q & A for this error. – msw Oct 08 '15 at 21:37