0

Change sign of elements in numpy array from a to b. I tried this.

import numpy as np
def do_negative(X, a, b):
    lst = []
    for i in X:
      if (a<i<b):
        lst.append(-i)
      else:
        lst.append(i)
    return X
test = np.array(range(9)).reshape(3,3)
do_negative(test, -1, 3).all()

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

Input data: from -1 to 3.

Output should be: np.array([[ 0, -1, -2], [-3, 4, 5], [ 6, 7, 8]])

0

2 Answers 2

1

Try this:

X is 2D numpy array,you have to make it 1D using flatten().Also you returning X instead of returning lst

def do_negative(X, a, b):
  lst = []
  for i in X.flatten():
    if (a < i <= b):
      lst.append(-1*i)
    else:
      lst.append(i)
  return np.array(lst).reshape(3,3)

Remove .all() when calling the function

do_negative(test, -1, 3)

Output:

array([[ 0, -1, -2],
       [-3,  4,  5],
       [ 6,  7,  8]])
Sign up to request clarification or add additional context in comments.

Comments

0

Using for loops to do element-wise operations on arrays is not how NumPy is supposed to be used.

This can be done quite easily with a whole-array operation:

def do_negative(x, a, b):
    result = x.copy()
    result[(a < x) & (x < b)] *= -1
    return result

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.