Skip to main content
 首页 » 编程设计

Python矢量化,如何使用numpy获取每一行的所有索引

2024年12月31日7java哥

我很难解决这个问题,主要问题是我正在运行模拟,所以对于 lops 主要是被禁止的,我有一个 NxN 的 numpy 数组,在这种情况下我的大约是 (10000x20) .

stoploss = 19.9 # condition to apply 
monte_carlo_simulation(20,1.08,10000,20) #which gives me that 10000x20 np array 
mask_trues = np.where(np.any((simulation <= stoploss) == True, axis=1)) # boolean mask 

我需要一些代码来制作一个新的 len(10000) 向量,它返回一个包含每一行所有位置的数组,让我们假设:

function([[False,True,True],[False,False,True]]) 
output = [[1,2],[2]] 

同样,主要问题在于没有使用循环。

请您参考如下方法:

就是这样:

list(map(np.where, my_array)) 

与 Kasrâmvd 解决方案的性能比较:

def f(a): 
    return list(map(np.where, a)) 
 
def g(a): 
    x, y = np.where(a) 
    return np.split(y, np.where(np.diff(x) != 0)[0] + 1) 
 
a = np.random.randint(2, size=(10000,20)) 
 
%timeit f(a) 
%timeit g(a) 
 
 
7.66 ms ± 38.1 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) 
13.3 ms ± 188 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)