gpt4 book ai didi

python - 在 numpy 数组中将特定值设置为零

转载 作者:太空宇宙 更新时间:2023-11-03 14:05:28 29 4
gpt4 key购买 nike

我有形状为 (4096,4096) 的 numpy 数组/矩阵和一个应设置为零的元素数组。我发现函数 numpy.in1d 工作正常但对我的计算来说非常慢。我想知道是否存在一些更快的执行方法,因为我需要在大量矩阵上重复此操作,因此每次优化都会有所帮助。

例子如下:

numpy 数组如下所示:

npArr = np.array([
[1, 4, 5, 5, 3],
[2, 5, 6, 6, 1],
[0, 0, 1, 0, 0],
[3, 3, 2, 4, 3]])

另一个数组是:

arr = np.array([3,5,8])

替换后的 numpy 数组 npArr 应该是这样的:

array([[ 1,  4,  0,  0,  0],
[ 2, 0, 6, 6, 1],
[ 0, 0, 1, 0, 0],
[ 0, 0, 2, 4, 0]])

最佳答案

这是使用 np.searchsorted 的替代方法-

def in1d_alternative_2D(npArr, arr):
idx = np.searchsorted(arr, npArr.ravel())
idx[idx==len(arr)] = 0
return arr[idx].reshape(npArr.shape) == npArr

它假设 arr 被排序。如果不是,我们需要排序,然后使用发布的方法。

sample 运行-

In [90]: npArr = np.array([[1, 4, 5, 5, 3],
...: [2, 5, 6, 6, 1],
...: [0, 0, 1, 0, 0],
...: [3, 3, 2, 14, 3]])
...:
...: arr = np.array([3,5,8])
...:

In [91]: in1d_alternative_2D(npArr, arr)
Out[91]:
array([[False, False, True, True, True],
[False, True, False, False, False],
[False, False, False, False, False],
[ True, True, False, False, True]], dtype=bool)

In [92]: npArr[in1d_alternative_2D(npArr, arr)] = 0

In [93]: npArr
Out[93]:
array([[ 1, 4, 0, 0, 0],
[ 2, 0, 6, 6, 1],
[ 0, 0, 1, 0, 0],
[ 0, 0, 2, 14, 0]])

针对 numpy.in1d 进行基准测试

使用 np.in1d 的等效解决方案是:

np.in1d(npArr, arr).reshape(npArr.shape)

让我们根据它来计算我们提议的时间,并验证问题中提到的尺寸的结果。

In [85]: # (4096, 4096) shaped 'npArr' and search array 'arr' of 1000 elems
...: npArr = np.random.randint(0,10000,(4096,4096))
...: arr = np.sort(np.random.choice(10000, 1000, replace=0 ))
...:

In [86]: out1 = np.in1d(npArr, arr).reshape(npArr.shape)
...: out2 = in1d_alternative_2D(npArr, arr)
...:

In [87]: np.allclose(out1, out2)
Out[87]: True

In [88]: %timeit np.in1d(npArr, arr).reshape(npArr.shape)
1 loops, best of 3: 3.04 s per loop

In [89]: %timeit in1d_alternative_2D(npArr, arr)
1 loops, best of 3: 1 s per loop

关于python - 在 numpy 数组中将特定值设置为零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43942943/

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