【发布时间】:2023-03-16 09:41:01
【问题描述】:
我有一个 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)
[1][1] 位置的值有 4 个邻居(黄色方块有 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
mask 变为:
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 来达到上述目的?
【问题讨论】:
-
对于邻居,你是只计算有多少相邻的单元格,还是将它们的值相加?
-
只是他们的数量(有多少 - 不是总和)
标签: python arrays python-3.x numpy neighbours