numpy-更新数组中的所有值,除了切片

发布于 2025-01-18 07:48:39 字数 372 浏览 3 评论 0原文

我有以下数组:

arr = np.array([[1, 1, 1, 1, 1, 1],
            [2, 0, 0, 0, 0, 2],
            [3, 0, 0, 0, 0, 3],
            [4, 4, 4, 4, 4, 4]])

inverse_slice = arr[1:3, 1:5]

我想更新数组中所有值的值,切片中的值除外。 例如,这可能是将所有值乘以 2,切片中的值除外(在本例中为 0 的矩形)。

我怎样才能有效地实现这一目标?

注意:性能至关重要,因为我正在处理的实际数组非常大,因此使用 Python for 循环进行迭代是不够的。

I have the following array:

arr = np.array([[1, 1, 1, 1, 1, 1],
            [2, 0, 0, 0, 0, 2],
            [3, 0, 0, 0, 0, 3],
            [4, 4, 4, 4, 4, 4]])

inverse_slice = arr[1:3, 1:5]

I want to update the values of all values in the array, execpt for the values in the slice.
For example, this could be multiplying all values with 2, exepct for values in the slice (the rectangle of 0's in this case).

How can I achieve this in an efficient manner?

NOTE: Performance is critical, as the actual array I'm processing is very large, so iteration using Python for-loops is not sufficient.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

辞别 2025-01-25 07:48:39

为什么不是这个?

arr2 = arr+1000
arr2[1:3, 1:5] = arr[1:3, 1:5]

arr2:

array([[1001, 1001, 1001, 1001, 1001, 1001],
       [1002,    0,    0,    0,    0, 1002],
       [1003,    0,    0,    0,    0, 1003],
       [1004, 1004, 1004, 1004, 1004, 1004]])

Why not this?

arr2 = arr+1000
arr2[1:3, 1:5] = arr[1:3, 1:5]

arr2:

array([[1001, 1001, 1001, 1001, 1001, 1001],
       [1002,    0,    0,    0,    0, 1002],
       [1003,    0,    0,    0,    0, 1003],
       [1004, 1004, 1004, 1004, 1004, 1004]])
不羁少年 2025-01-25 07:48:39

您可以通过块来完成此操作。

可能不是最优雅的方法,尽管您可以在需要影响的确切单元格上循环,同时根据未触及的矩形的大小保持小于O(n^2)的复杂性:

x_min, x_max = (1, 3)
y_min, y_max = (1, 5)
f = <your function>

arr[:x_min, :] = f(arr[:x_min, :])
arr[x_min:x_max, :y_min] = f(arr[x_min:x_max, :y_min])
arr[x_min:x_max, y_max:] = f(arr[x_min:x_max, y_max:])
arr[x_max:, :] = f(arr[x_max:, :])

You could do this working by chunks.

Probably not the most elegant way to do it, though you can cycle over the exact cells you need to affect, while keeping a less than O(n^2) complexity depending on the size of the untouched rectangle:

x_min, x_max = (1, 3)
y_min, y_max = (1, 5)
f = <your function>

arr[:x_min, :] = f(arr[:x_min, :])
arr[x_min:x_max, :y_min] = f(arr[x_min:x_max, :y_min])
arr[x_min:x_max, y_max:] = f(arr[x_min:x_max, y_max:])
arr[x_max:, :] = f(arr[x_max:, :])
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文