efficient loop over numpy array

前端 未结 8 1620
轮回少年
轮回少年 2021-01-06 02:05

Versions of this question have already been asked but I have not found a satisfactory answer.

Problem: given a large numpy vector, find indices of t

8条回答
  •  长发绾君心
    2021-01-06 02:21

    The obvious question is why you want to do this in this way. NumPy arrays are intended to be opaque data structures – by this I mean NumPy arrays are intended to be created inside the NumPy system and then operations sent in to the NumPy subsystem to deliver a result. i.e. NumPy should be a black box into which you throw requests and out come results.

    So given the code above I am not at all suprised that NumPy performance is worse than dreadful.

    The following should be effectively what you want, I believe, but done the NumPy way:

    import numpy as np
    
    N = 10000
    vect = np.arange(float(N))
    vect[N/2] = 1
    vect[N/4] = 1
    
    print([np.where(a == vect)[0] for a in vect][1])
    
    # Delivers [1, 2500, 5000]
    

提交回复
热议问题