Home > Back-end >  How can I construct an if statement for numpy arrays' elements comparison, to produce a new arr
How can I construct an if statement for numpy arrays' elements comparison, to produce a new arr

Time:01-27

import numpy as np


a = np.array([[3.5,6,8,2]])
b = np.array([[6,2,8,2]])
c = np.array([[2,3,7,5]])
d = np.array([[3,2,5,1]])
if a > b:
    e = 2*a 6*c
else:
    e = 3*c   4*d

print(e)

then I got

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

and if I type in print(e), I got

[2, 3, 7, 5, 2, 3, 7, 5, 2, 3, 7, 5, 3, 2, 5, 1, 3, 2, 5, 1, 3, 2, 5, 1, 3, 2, 5, 1]

The e I want to construct is an array that has the same dimension with a,b,c,d , and the if statement that decides what equation will be used to make each element.

In other words, for the elements in of the first place of a and b: 3.5<6, so e = 3c 4d = 32 43 = 18 For the second elements: 6>2, e = 2a 6c = 26 63 = 30

Third: 8=8, e = 3c 4d = 37 45 = 41

Fourth: 2 = 2, e = 3c 4d = 35 41 = 19

e = [18,30,41,19]

I tried to find someone who asked about constructing a script doing such things, but I could find none, and all numpy questions about if statement(or equivalent) did not help. Thanks.(It seems that a.all or a.any from the python recommendation did not help as well.)

CodePudding user response:

Use numpy.where:

Return elements chosen from x or y depending on condition.

e = np.where(a > b, 2*a 6*c, 3*c   4*d)
  •  Tags:  
  • Related