如何在没有嵌套for循环的情况下更快地减少冗余

2024-06-17 15:11:12 发布

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

我有一大块代码,我想加快速度。我一直在使用张量流一点,如果这将是一个很好的方式来解决这个问题。这是我正在进行的大型模拟的一部分代码。然而,这段代码运行时间太长。我有一种方法可以改变它们在曲面上被分割的频率,现在分辨率降低了10倍,这个循环运行了一个多小时。有没有人有什么建议可以加快速度?你知道吗

Points = PlanesList[0:3,0:3]
Indices = np.array([[0],[1],[2]])
print(np.prod(PlanesList[0,:].shape))
for k in range(1,int(np.prod(PlanesList[0,:].shape)/3)+1):
    for ind in range(1,int(np.prod(Points.shape)/3)+1):
        truths = np.array([False,False,False])
        if np.all(PlanesList[0:3,(3*k-3)] == Points[0:3,ind-1]):
            index1=ind-1
            truths[0] = True
        if np.all(PlanesList[0:3,(3*k-2)] == Points[0:3,ind-1]):
            index2=ind-1
            truths[1] = True
        if np.all(PlanesList[0:3,(3*k-1)] == Points[0:3,ind-1]):
            index3=ind-1
            truths[2] = True
    if truths[0] == False:
        Points = np.column_stack([Points,PlanesList[0:3,(3*k-3)]])
        index1 = np.prod(Points[0,:].shape)-1
    if truths[1] == False:
        Points = np.column_stack([Points,PlanesList[0:3,(3*k-2)]])
        index2 = np.prod(Points[0,:].shape)-1
    if truths[2] == False:
        Points = np.column_stack([Points,PlanesList[0:3,(3*k-1)]])
        index3 = np.prod(Points[0,:].shape)-1
    Tempind = np.array([[int(index1)],[int(index2)],[int(index3)]])
    Indices = np.column_stack([Indices,Tempind])

此代码的目的是从数组PlanesList中删除冗余。由于我创建数组的方式,我还没有想出一种无冗余的方法来形成它。PlanesList是一个包含三维三角形集的数组,在后面的模拟中,我需要能够定位这些三角形。第0行是X坐标,第1行是Y坐标,第2行是Z坐标。PlanesList是一个二维数组,包含60000列(20000个三角形)和3行。你知道吗


Tags: 代码falseifstacknpcolumnprod数组
1条回答
网友
1楼 · 发布于 2024-06-17 15:11:12

要将numpy数组中的相同列缩减为一次出现,可以将np.uniqueaxis参数一起使用。你知道吗

示例数据:

a = np.random.randint(0, 10, (3,10)) 
a[:,3] = a[:,0]  # Duplicate one column

减少:

a_reduced = np.unique(a, axis=1)

请注意,这将对数组进行排序。你知道吗

另外,请注意,axis参数是在numpy版本1.13.0中添加的。我假设底层实现是快速的,尽管可能存在专门针对您的问题的更快的解决方案。你知道吗


编辑:如果您想知道缩减点在完整数组中的索引,请使用return_index参数:

a_reduced, a_indices = np.unique(a, axis=1, return_index=True)

相关问题 更多 >