0

I checked out the threads with this error message, but the solutions didn't really apply to my case

Here's my code. I saw in the debugger that the arrays work fine, they have values etc, but the condition fails.

matrix = np.zeros((self.data_set.nfeatures, self.data_set.A.shape[0], self.R.shape[0]))
for i in range(self.data_set.nfeatures):

    for a in range(self.data_set.A.shape[0]):

        for b in range(self.R.shape[0]):

            if self.R[1]-self.R[0] <= self.Q[i]: # Program crashes here
                matrix[i][a][b] = 0
            elif self.R[1]-self.R[0] >= self.P[i]:
                matrix[i][a][b] = 1
            else:
                matrix[i][a][b]= self.R[1]-self.R[0]-self.Q[i]

Error message: if self.R[1]-self.R[0] <= self.Q[i]: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Barmar
  • 741,623
  • 53
  • 500
  • 612
loirtiV
  • 1
  • 1
  • 1
    There are hundreds of questions about that error message. What research did you do before posting? – Barmar Jan 20 '22 at 20:24
  • If you're looping over a numpy array, you're usually doing something wrong. Use its built-in methods to operate on all matching rows. – Barmar Jan 20 '22 at 20:25
  • the problem usually referred to logical ANDs, but i don't have those here – loirtiV Jan 20 '22 at 20:26
  • It's coming from trying to use the result of a comparison in an `if` statement. When you compare two arrays, you get an array. – Barmar Jan 20 '22 at 20:28
  • `self.R[1]-self.R[0] <= self.Q[i]` is subtracting two arrays and comparing that with another array, so it returns an array of truth values. – Barmar Jan 20 '22 at 20:35
  • 1
    You probably want to use `np.where()` – Barmar Jan 20 '22 at 20:36
  • The problem can arise anywhere that expects a simple True/False, and the condition is a boolean array with more than one value. Python `and` is one, `if` is just a common problem case. The problem is more subtle when combining several comparisons with `np.logical_and`. Before seeking a fix, make sure you understand the problem – hpaulj Jan 20 '22 at 21:06
  • Does this answer your question? [Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()](https://stackoverflow.com/questions/36921951/truth-value-of-a-series-is-ambiguous-use-a-empty-a-bool-a-item-a-any-o) – rikyeah Jan 30 '22 at 19:12

0 Answers0