[英]How to count neighbouring cells in a numpy array using try-except?
I have a numpy array: 我有一个numpy的数组:
x = np.random.rand(4, 5)
I would like to create an array showing how many neighbouring values are there for each value in the original array . 我想创建一个数组,显示原始数组中每个值有多少个相邻值 。 By neighbouring I mean:
邻居,我的意思是:
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)
The value at position [1][1]
has 4 neighbours (the yellow square has 4 adjacent green cells). 位置
[1][1]
有4个邻居(黄色正方形有4个相邻的绿色单元格)。
A solution which works: 有效的解决方案:
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
becomes: mask
变成:
array([[2, 3, 3, 3, 2],
[3, 4, 4, 4, 3],
[3, 4, 4, 4, 3],
[2, 3, 3, 3, 2]])
Now I try to create the same array with try-except
: 现在,我尝试使用
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)
Giving thre resulting numofneighbours
array: 给结果
numofneighbours
数组:
array([[4, 4, 4, 4, 3],
[4, 4, 4, 4, 3],
[4, 4, 4, 4, 3],
[3, 3, 3, 3, 2]])
Which is not equal to mask
, as I expected it to be. 正如我所期望的,这不等于
mask
。
What am I doing wrong here or how should I use try-except for the purpose described above? 我在这里做错了什么,还是应该为上述目的使用try-except?
The problem here is that numpy allows negative indexing. 这里的问题是numpy允许负索引。
a[-1]
stands for the last value in a
which is why the first numbers in your array are not decreased. a[-1]
代表在最后一个值a
这就是为什么你的数组中的第一个数字不下降。
I think the first way you described is cleaner and faster than the try-except method and you should just use that. 我认为您描述的第一种方法比try-except方法更干净,更快捷,您应该只使用它。
Realised that index-1
and INDEX-1
indicies are still valid when index
and INDEX
are equal to 0, they just have the value -1
, making it a valid array index even though the value they are refering to is not neighbouring the value referred to by index
and INDEX
. 意识到当
index
和INDEX
等于0时index-1
和INDEX-1
索引仍然有效,它们只有值-1
,即使它们所引用的值不与所引用的值相邻,也使其成为有效的数组索引到index
和INDEX
。 My fix is the following: 我的解决方法如下:
x = np.random.rand(4, 5)
numofneighbours=[]
for index, each in enumerate(x):
row=[]
for INDEX, EACH in enumerate(each):
c=4
try:x[index+1][INDEX]
except:c-=1
try:x[index][INDEX+1]
except:c-=1
try:x[index-1][INDEX]
except:c-=1
if (index-1)<0: c-=1
try:x[index][INDEX-1]
except:c-=1
if (INDEX-1)<0: c-=1
row.append(c)
numofneighbours.append(row)
numofneighbours=np.asarray(numofneighbours)
This gives: 这给出:
array([[2, 3, 3, 3, 2],
[3, 4, 4, 4, 3],
[3, 4, 4, 4, 3],
[2, 3, 3, 3, 2]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.