find function matlab in numpy/scipy

前端 未结 3 624
不思量自难忘°
不思量自难忘° 2021-02-15 06:09

Is there an equivalent function of find(A>9,1) from matlab for numpy/scipy. I know that there is the nonzero function in numpy but what I need is th

3条回答
  •  情深已故
    2021-02-15 06:55

    I'm sure these are all great answers but I wasn't able to make use of them. However, I found another thread that partially answers this: MATLAB-style find() function in Python

    John posted the following code that accounts for the first argument of find, in your case A>9 ---find(A>9,1)-- but not the second argument.

    I altered John's code which I believe accounts for the second argument ",1"

    def indices(a, func):
        return [i for (i, val) in enumerate(a) if func(val)]
    a = [1,2,3,9,6,4,3,10]
    threshold = indices(a, lambda y: y >= 9)[0]
    

    This returns threshold=3. My understanding is that Python's index starts at 0... so it's the equivalent of matlab saying 4. You can change the value of the index being called by changing the number in the brackets ie [1], [2], etc instead of [0].

    John's original code:

    def indices(a, func):
        return [i for (i, val) in enumerate(a) if func(val)]
    
    a = [1, 2, 3, 1, 2, 3, 1, 2, 3]
    
    inds = indices(a, lambda x: x > 2)
    

    which returns >>> inds [2, 5, 8]

提交回复
热议问题