Python Forum
Compare each element of an array in a logic statement without using a for loop
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Compare each element of an array in a logic statement without using a for loop
#2
Your problem is not the comparison, it is the result of the comparison. When you compare two numpy arrays the result is an array of bool, not True or False
import numpy as np

a = np.array([1, 2, 3])
b = np.array([2, 3, 4])
print(a < b)

if a < b:
    print('True')
Output:
[ True True True] Traceback (most recent call last): File "c:/Users/hystadd/Documents/python/sandbox/junk.py", line 7, in <module> if a < b: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
The comparison worked fine, producing an array [ True True True]. This is very similar to what happens when you compare arrays in MATLAB (just replace True/False with 1/0). The problem is converting an array of bool to True or False. The error message tells you how to do this.
import numpy as np

a = np.array([1, 2, 3])
b = np.array([2, 3, 4])
print(a < b)

if all(a < b):
    print('True')
Reply


Messages In This Thread
RE: Compare each element of an array in a logic statement without using a for loop - by deanhystad - Mar-31-2021, 03:57 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Elegant way to apply each element of an array to a dataframe? sawtooth500 7 441 Mar-29-2024, 05:51 PM
Last Post: deanhystad
  Loop over an an array of array Chendipeter 1 597 Nov-28-2023, 06:37 PM
Last Post: deanhystad
  Loop through values and compare edroche3rd 6 704 Oct-18-2023, 04:04 PM
Last Post: edroche3rd
Photo Python code: While loop with if statement HAMOUDA 1 585 Sep-18-2023, 11:18 AM
Last Post: deanhystad
  Trying to compare string values in an if statement israelsattleen 1 568 Jul-08-2023, 03:49 PM
Last Post: deanhystad
  Multiply and Addition in the same loop statement with logic. joelraj 2 1,051 Feb-02-2023, 04:33 AM
Last Post: deanhystad
  compare and find the nearest element ? mr_gentle_sausage 4 1,063 Jan-15-2023, 07:11 AM
Last Post: DPaul
  Loop different actions for an array Tibovdv 4 2,776 Mar-25-2021, 06:46 PM
Last Post: jefsummers
Exclamation Compare values in a for loop. penahuse 1 2,380 Feb-22-2021, 07:01 AM
Last Post: buran
  how to create pythonic codes including for loop and if statement? aupres 1 1,932 Jan-02-2021, 06:10 AM
Last Post: Gribouillis

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020