2

Is there a way to find the indices where exceptions are thrown using np.where? For example:

a = np.array(['0.0', 'hi', '2012:13', '2013/04/05', '9.8', '7.6'])

print np.where(np.float64(a)==Exception)[0][-1]

I would hope would provide this output:

[ 0.  4.  5.]

However, it gives this output:

ValueError: could not convert string to float: hi

This script can provide the answer, but it seems quite inefficient and much less pythonic:

b = np.array([])
for i, x in enumerate(a):
    try:
        np.float64(x)
    except:
        b = np.hstack((b,i))
print b
chase
  • 3,592
  • 8
  • 37
  • 58

1 Answers1

1

You could define a function

def is_number(s):
    try:
        np.float64(s)
        return True
    except ValueError:
        return False

and then collect your floats via a list comprehension

print np.array([np.float64(x) for x in a if is_number(x)])

If this is better in terms of readability or compactness of code will depend on whether you can use the function at several places in your code. What concerns efficiency I would expect this solution to be faster for large problem sizes; since I am afraid that hstack has O(len(b)) complexity, which would mean O(len(b)**2) for the script you currently have.

Community
  • 1
  • 1
matec
  • 1,316
  • 1
  • 10
  • 22
  • Thanks, I hadn't seen the link you provided and it makes me feel a little better about using this approach. At first I was searching for a numpy one liner, since it seems like those are the most efficient and are many times pythonic or easily understood. However, this appears to be agreed upon as the most acceptable manner to do this. – chase Jan 27 '14 at 14:50