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

2024-05-15 22:26:29 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

我需要一些代码来生成len(10000)的新向量,它返回一个数组,其中包含每行的所有位置,让suposse:

^{pr2}$

同样,主要的问题在于没有使用循环,这要归功于所有的提前。在


Tags: tonumpynp情况mask数组conditionmonte
3条回答

以下是使用np.split()np.diff()的一种方法:

x, y = np.where(boolean_array)
np.split(y, np.where(np.diff(x) != 0)[0] + 1)

演示:

^{pr2}$

简单地说:

list(map(np.where, my_array))

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

^{pr2}$

为了完整起见,我将演示稀疏矩阵方法:

In [57]: A = np.array([[False,True,True],[False,False,True]])
In [58]: A
Out[58]: 
array([[False,  True,  True],
       [False, False,  True]])
In [59]: M = sparse.lil_matrix(A)
In [60]: M
Out[60]: 
<2x3 sparse matrix of type '<class 'numpy.bool_'>'
    with 3 stored elements in LInked List format>
In [61]: M.data
Out[61]: array([list([True, True]), list([True])], dtype=object)
In [62]: M.rows
Out[62]: array([list([1, 2]), list([2])], dtype=object)

做一个大的稀疏的:

^{pr2}$

粗略测试:

In [66]: arr = BM.A
In [67]: timeit sparse.lil_matrix(arr)
19.5 ms ± 421 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
In [68]: timeit list(map(np.where,arr))
11 ms ± 55.6 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
In [69]: %%timeit
    ...: x,y = np.where(arr)
    ...: np.split(y, np.where(np.diff(x) != 0)[0] + 1)
    ...: 
13.8 ms ± 24.3 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

生成csr稀疏格式矩阵的速度更快:

In [70]: timeit sparse.csr_matrix(arr)
2.68 ms ± 120 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [71]: Mr = sparse.csr_matrix(arr)
In [72]: Mr.indices
Out[72]: array([ 3,  6, 15, ...,  8, 16, 11], dtype=int32)
In [73]: Mr.indptr
Out[73]: array([    0,     1,     1, ...,  9999, 10000, 10000], dtype=int32)
In [74]: np.where(arr)[1]
Out[74]: array([ 3,  6, 15, ...,  8, 16, 11])

它的indices就像列where,而{}则类似于{}indices。在

相关问题 更多 >