user3503704
user3503704

Reputation:

How do you have if statements with a numpy array?

I have the following input file 'r1'

14 14
15 15

I would like to create the following output file 'r2'.

14 14 less than 15
15 15 equal to 15

I am trying to do so using the following code.

import numpy as np

s=open('r1')
r=open('r2','w+')

r1=np.loadtxt(s)
atim=r1[:,[0]]
alat=r1[:,[1]]

if atim<15 and alat<15:
    print >> r,atim,alat,'less than 15'

if atim==15 and alat==15:
    print >> r,atim,alat,'equal to 15'

However, when I run the program I get the following error if atim<15 and alat<15: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Upvotes: 0

Views: 4187

Answers (3)

Akavall
Akavall

Reputation: 86198

import numpy as np

r1 = np.array([[11, 15],
               [15, 15],
               [14, 14]])

equal_to_15 = (r1[:,0] == 15) & (r1[:,1] == 15)
less_than_15 = (r1[:,0] < 15) & (r1[:,1] < 15)

Result:

>>> equal_to_15
array([False,  True, False], dtype=bool)
>>> less_than_15
array([False, False,  True], dtype=bool)

Error Message:

When you compare an array to integer you get a boolean array.

>>> np.array([13, 15]) == 15
array([False,  True], dtype=bool)
>>> if _:
...     print 'Hi'
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

And numpy does not evaluate the whole array for truthness, but if we did:

>>> if (np.array([13, 15]) == 15).any():
...     print 'Hi'
... 
Hi

Upvotes: 0

acushner
acushner

Reputation: 9946

with numpy, it's pretty easy:

[(a < 15).all() for a in r1] 

or

[(a == 15).all() for a in r1] 

Upvotes: 0

dabhaid
dabhaid

Reputation: 3879

You want to do a comparison like

all(i < 15 for i in r1[0])
all(i == 15 for i in r1[0])

so you could do:

for row in len(r1):
    if all(i < 15 for i in r1[row]):
        print >> r,r1[row][0], r1[row][1], 'less than 15'
    if all(i == 15 for i in r1[row]):
        print >> r,r1[row][0], r1[row][1], 'equal to 15'

Upvotes: 1

Related Questions