【问题标题】:How to count neighbouring cells in a numpy array using try-except?如何使用try-except计算numpy数组中的相邻单元格?
【发布时间】: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


【解决方案1】:

这里的问题是 numpy 允许负索引。 a[-1] 代表 a 中的最后一个值,这就是数组中的第一个数字没有减少的原因。

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

【讨论】:

  • 谢谢,相信你的回答是对的。我还打算用 try-except 来处理其他问题,这应该是一个更复杂问题的简化问题。
【解决方案2】:

意识到当 index 和 INDEX 等于 0 时,index-1 和 INDEX-1 索引仍然有效,它们只有值 -1,即使它们的值也是有效的数组索引引用与index 和INDEX 引用的值不相邻。我的解决方法如下:

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)

这给出了:

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

【讨论】:

    猜你喜欢
    • 2012-09-18
    • 1970-01-01
    • 2016-07-21
    • 1970-01-01
    • 2019-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多