0

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()

1
  • 1
    That's a pretty good error message, did you try following up on the suggestions you got there? Commented Apr 9, 2014 at 13:06

3 Answers 3

1

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'
Sign up to request clarification or add additional context in comments.

Comments

0

with numpy, it's pretty easy:

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

or

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

Comments

0
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

Comments