gpt4 book ai didi

python - 如何使用 try- except 计算 numpy 数组中的相邻单元格?

转载 作者:行者123 更新时间:2023-12-01 01:09:40 24 4
gpt4 key购买 nike

我有一个 numpy 数组:

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

我想创建一个数组,显示原始数组中每个值有多少个相邻值。我所说的邻居是指:

example=np.array([[0,1,0,0,0],
[1,2,1,0,0],
[0,1,0,0,0],
[0,0,0,0,0]])

plt.imshow(example)

enter image description here

位置 [1][1] 处的值有 4 个邻居(黄色方 block 有 4 个相邻的绿色单元格)。

有效的解决方案:

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

mask = 4*np.ones(x.shape, dtype=int)

mask[0][:]=3
mask[-1][:]=3

for each in mask: each[0]=3
for each in mask: each[-1]=3

mask[0][0]=2
mask[0][-1]=2
mask[-1][0]=2
mask[-1][-1]=2

掩码变为:

array([[2, 3, 3, 3, 2],
[3, 4, 4, 4, 3],
[3, 4, 4, 4, 3],
[2, 3, 3, 3, 2]])

现在我尝试使用 try- except 创建相同的数组:

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

numofneighbours=[]

for index, each in enumerate(x):
row=[]
for INDEX, EACH in enumerate(each):

c=4
try:ap[index+1][INDEX]
except:c-=1

try:ap[index][INDEX+1]
except:c-=1

try:ap[index-1][INDEX]
except:c-=1

try:ap[index][INDEX-1]
except:c-=1

row.append(c)

numofneighbours.append(row)
numofneighbours=np.asarray(numofneighbours)

给出结果 numofneighbours 数组:

array([[4, 4, 4, 4, 3],
[4, 4, 4, 4, 3],
[4, 4, 4, 4, 3],
[3, 3, 3, 3, 2]])

这不等于 mask,正如我所期望的那样。

我在这里做错了什么或者我应该如何使用 try- except 来达到上述目的?

最佳答案

这里的问题是 numpy 允许负索引。 a[-1] 代表 a 中的最后一个值,这就是为什么数组中的第一个数字不会减少。

我认为您描述的第一种方法比 try- except 方法更干净、更快,您应该使用它。

关于python - 如何使用 try- except 计算 numpy 数组中的相邻单元格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54981645/

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