gpt4 book ai didi

python - 如何在需要唯一性和非唯一性检查的Python循环中向量化这个循环?

转载 作者:行者123 更新时间:2023-12-01 02:36:52 27 4
gpt4 key购买 nike

我有一个大小为 3xn 的 numpy 数组(edges),它恰好包含两行,其中该行的前两个元素可能匹配,也可能不匹配匹配。我正在根据这个标准计算一些东西。我的基于 for 循环的代码遵循这些原则

mat = np.zeros((edges.shape[0],2),dtype=np.int64)
counter = 0;
for i in range(edges.shape[0]):
for j in range(i+1,edges.shape[0]):
if edges[i,0]==edges[j,0] and edges[i,1]==edges[j,1] and edges[i,2] != edges[j,2]:
mat[2*counter,0] = i % nof
mat[2*counter,1] = i // nof

mat[2*counter+1,0] = j % nof
mat[2*counter+1,1] = j // nof
counter +=1
break

其中nof是一个特定的数字。如何使用 numpy 加速此代码?我无法使用 np.unique ,因为此代码需要唯一性以及非唯一性检查。

例如,给定:

edges = np.array([
[1,2,13],
[4,5,15],
[5,6,18],
[1,2,12],
[4,5,15],
[5,6,18],
])

其中每行的前两个元素可以在另一行中找到(即它们恰好重复两次)并且nof=1,上面的代码给出以下结果

[[0 0]
[0 3]
[0 0]
[0 0]]

最佳答案

我还没有了解您如何设置mat,但我怀疑前两列的词法排序可能会有所帮助:

In [512]: edges = np.array([
...: [1,2,13],
...: [4,5,15],
...: [5,6,18],
...: [1,2,12],
...: [4,5,15],
...: [5,6,18],
...: ])
...:
In [513]: np.lexsort((edges[:,1],edges[:,0]))
Out[513]: array([0, 3, 1, 4, 2, 5], dtype=int32)
In [514]: edges[_,:] # sedges (below)
Out[514]:
array([[ 1, 2, 13],
[ 1, 2, 12],
[ 4, 5, 15],
[ 4, 5, 15],
[ 5, 6, 18],
[ 5, 6, 18]])

现在所有匹配的行都在一起。

如果总是有 2 个匹配项,则可以收集这些对并将其重新整形为 2 列数组。

In [516]: sedges[:,2].reshape(-1,2)
Out[516]:
array([[13, 12],
[15, 15],
[18, 18]])

或者,您仍然可以迭代,但不必检查那么远。

<小时/>排序列表上的

argsort 返回相反的排序:

In [519]: np.lexsort((edges[:,1],edges[:,0]))
Out[519]: array([0, 3, 1, 4, 2, 5], dtype=int32)
In [520]: np.argsort(_)
Out[520]: array([0, 2, 4, 1, 3, 5], dtype=int32)
In [521]: sedges[_,:]
Out[521]:
array([[ 1, 2, 13],
[ 4, 5, 15],
[ 5, 6, 18],
[ 1, 2, 12],
[ 4, 5, 15],
[ 5, 6, 18]])

关于python - 如何在需要唯一性和非唯一性检查的Python循环中向量化这个循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46125252/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com