gpt4 book ai didi

python - 为 numpy 数组的每个 "other"字段 ((i+j)%2==0) 添加值

转载 作者:太空狗 更新时间:2023-10-29 20:15:22 24 4
gpt4 key购买 nike

我有一个 m-by-n numpy 数组,我想将 1.0 添加到所有条目 [i, j](i + j) % 2 == 0 时,即“每隔一个方格”。

我当然可以简单地遍历字段

import numpy as np

a = np.random.rand(5, 4)

for i in range(a.shape[0]):
for j in range(a.shape[1]):
if (i + j) % 2 == 0:
a[i, j] += 1.0

但不用说这真的很慢。

知道如何改进吗?

最佳答案

你可以很容易地分两步完成操作,比如

import numpy as np

a = np.zeros((5, 14))

# Even rows, odd columns
a[::2, 1::2] += 1
# Odd rows, even columns
a[1::2, ::2] += 1

print a

关于python - 为 numpy 数组的每个 "other"字段 ((i+j)%2==0) 添加值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38204283/

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