python - 如何膨胀 numpy 数组

标签 python numpy array-broadcasting

我有一个形状为(1000,3)的点的numpy数组 其中轴 1 的值为 [x,y,1]

这些点位于网格上的离散值,因此示例数组如下所示:

array=([1,2,1],[4,5,1],[2,3,1],...,[xN,yN,1])

我想扩大这个二维数组,我的意思是,对于数组中的每个[x,y,1]坐标,如果[x±1,y± 1,1]不在数组中将其追加到数组中。

目前我正在使用以下代码执行此操作:

np.append(array, [array[:,0],array[:,1]+1,1])
np.append(array, [array[:,0]+1,array[:,1],1])
np.append(array, [array[:,0]+1,array[:,1]+1,1])
np.append(array, [array[:,0]-1,array[:,1],1])
np.append(array, [array[:,0],array[:,1]-1,1])
np.append(array, [array[:,0]-1,array[:,1]-1,1])
np.append(array, [array[:,0]+1,array[:,1]-1,1])
np.append(array, [array[:,0]-1,array[:,1]+1,1])

然后我使用np.unique(array)来减少唯一的元素。这个方法是可行的,但是在超过100000个点的大型数组上运行速度太慢,而且感觉不是一个顺利的解决方案。必须有一种方法可以做到这一点,而无需重复这么多点,然后必须找到所有唯一的实例。有没有一种不同的(阅读:更快)的方式来完成我正在做的事情?

最佳答案

2000 x 4000 x 200 只需使用查找表即可实现。与 np.unique 方法相比,在略低于一百万个坐标时,我的速度提高了约 5 倍。

lookup table:  2.18715, np.unique: 11.40247

代码:

import numpy as np
from numpy.lib.stride_tricks import as_strided
from time import time

coords = np.unique(np.random.randint(0, 2000*4000*200, (1000000,)))
coords = np.c_[coords // (4000*200), (coords // 200) % 4000, coords % 200]

t = [time()]

ws = np.empty((2002, 4002, 202), dtype=np.uint8)
ws = as_strided(ws, (2000, 4000, 200, 3, 3, 3), 2 * ws.strides)

ws[tuple(coords.T)] = np.arange(27).reshape(3, 3, 3)
unq = ws[tuple(coords.T)] == np.arange(27).reshape(3, 3, 3)
result = (coords[:, None, None, None, :] + np.moveaxis(np.indices((3, 3, 3)) - 1, 0, -1))[unq]
del ws

t.append(time())

result2 = np.unique((coords[:, None, None, None, :] + np.moveaxis(np.indices((3, 3, 3)) - 1, 0, -1)).reshape(-1, 3), axis = 0)

t.append(time())

print('lookup table: {:8.5f}, np.unique: {:8.5f}'.format(*np.diff(t)))

关于python - 如何膨胀 numpy 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48086586/

相关文章:

python - numpy.append() 的困难。当我自己在 IDLE 中输入它时它有效,但在运行时无效

python - 如何从列表列表中制作平面列表?

python - 将每一行乘以不同的旋转矩阵

python - Python Twisted中的互斥量

python - 如何使用 google-api-python-client 设置 BigQuery 配置属性?

python - 如何找到二维矩阵的两条对角线?

python - 计算忽略 NaN 值的行的最小值

python - 为什么通过 pytorch 张量循环如此缓慢(与 Numpy 相比)?

python - 定义 numpy 索引数组

python - numpy knn 与向量化嵌套矩阵