在Python中获取满足条件的矩阵的行索引

2024-09-27 00:22:39 发布

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

我一直试图得到矩阵(A)中包含元素nd的所有行索引。你知道吗

A的大小是4米×4,这个操作大约需要12秒。你知道吗

链接到文件:data

# Download the file named elementconnectivity before running this small script 


A=np.loadtxt('elementconnectivity') 
A=A.astype(int)
nd=1103
v=[i for i in range(len(A)) if nd in A[i]]

有没有更快的方法来实现这一点?你知道吗


Tags: 文件thein元素data链接download矩阵
2条回答

我认为更好的方法是使用迭代器而不是列表

idxs = (i for i in xrange(len(A)) if nd in A[i])
idxs.next()

因为您使用的是numpy,所以使用更多的numpy函数可以大大加快速度。您当前在我的系统上的方法:

%timeit v=[i for i in range(len(A)) if nd in A[i]]
1 loop, best of 3: 4.23 s per loop

相反,这要快40倍:

%timeit v = np.where(np.sum((A == nd), axis=1) > 0)
10 loops, best of 3: 92.2 ms per loop

您还可以查看np.in1d,它类似于我上面使用的A == nd,但是可以与列表(类似于A==nd1或nd2或nd3)进行比较。你知道吗

相关问题 更多 >

    热门问题