0

suppose I have this function:

a = np.array([-2,1,-5,2])
if a <0:
    a += 10
print (a)

why I am getting this error.

If I pass only one value then it is okey. How to solve this problem?

thank you in advance.

Fabio Lamanna
  • 20,504
  • 24
  • 90
  • 122
bikuser
  • 2,013
  • 4
  • 33
  • 57
  • 2
    You're comparing list with an integer, which will give you a type error. This question is really unclear, but if you want to use `any` or `all`, as in the title, use `if any(a):` or `if all(a):`. And please elaborate on what you're trying to do. – FlipTack Dec 29 '16 at 14:56
  • 1
    You are trying to compare ONE value with MANY. It is not possible. – Psytho Dec 29 '16 at 14:57
  • There are many duplicates on SO that discuss this error message. – Alex Riley Dec 29 '16 at 14:59
  • 1
    @ajcr In this case you've linked to the wrong duplicate (not saying it isn't a duplicate, it almost certainly is). It's **not** about evaluating the boolean value of the array. – MSeifert Dec 29 '16 at 15:03
  • There may well be a better duplicate to link to, but I don't agree that the linked duplicate is necessarily wrong. Regardless of what the correct approach to incrementing certain values of an array may be, the OP *is* evaluating the boolean value of the array `a` in the code (although probably unintentionally). The OP asks why the error arises here and the linked duplicate explains the reason why. – Alex Riley Dec 29 '16 at 15:29

2 Answers2

4

numpy does element wise comparison and addition and is vectorized. A direct translation of if-else in numpy is np.where():

import numpy as np
a = np.where(a < 0, a + 10, a)
# array([8, 1, 5, 2])
Psidom
  • 209,562
  • 33
  • 339
  • 356
2

You can simply increment by indexing with a boolean array (a < 0):

a[a < 0] += 10
MSeifert
  • 145,886
  • 38
  • 333
  • 352