I'm an undergrad at university particapting in a research credit with a professor, so this is pretty much an independent project for me.
I am converting a matlab script into a python (3.4) script for easier use on the rest of my project. The 'find' function is employed in the script, like so:
keyindx = find(summags>=cumthresh,1)
Keyindx would contain the location of the first value inside summag above cumthresh
So, as an example:
summags = [ 1 4 8 16 19]
cumthresh = 5
then keyindx would return with an index of 2, whose element corresponds to 8.
My question is, I am trying to find a similar function in python (I am also using numpy and can use whatever library I need) that will work the same way. I mean, coming from a background in C I know how to get everything I need, but I figure there's a better way to do this then just write some C style code.
So, any hints about where to look in the python docs and about finding useful functions in general?
2 Answers 2
A quick search led me to the argwhere function which you can combine with [0] to get the first index satisfying your condition. For example,
>> import numpy as np
>> x = np.array(range(1,10))
>> np.argwhere(x > 5)[0]
array([5])
This isn't quite the same as saying
find(x > 5, 1)
in MATLAB, since the Python code will throw an IndexError if none of the values satisfy your condition (whereas MATLAB returns an empty array). However, you can catch this and deal with it appropriately, for example
try:
ind = np.argwhere(x > 5)[0]
except IndexError:
ind = np.array([1])
Comments
np.nonzero(x) gives a tuple of the nonzero indices. That value can then be used to index any array of the matching size.
In [1262]: x=np.arange(6).reshape(2,3)
In [1263]: ind=np.nonzero(x>3)
In [1264]: x[ind]
Out[1264]: array([4, 5])
In [1265]: ind
Out[1265]: (array([1, 1], dtype=int32), array([1, 2], dtype=int32))
findfunction does!