San*_*yak 8 python numpy matrix
我需要找到一个单元格中所有相邻元素的总和,比如说getsumofneighbors(matrix, i, j):
'M*N matrix'
[[0 1 0]
[2 0 1]
[0 4 0]
[0 0 0]]
Run Code Online (Sandbox Code Playgroud)
最近元素的总和[0][0]是3
在[1][0]5点
在[1][1]8点
是否有一个python库来查找给定单元格旁边所有元素的总和?
War*_*ser 10
如果您不介意对scipy的依赖,可以使用scipy.ndimage.convolve如下:
In [475]: a
Out[475]:
array([[0, 1, 0],
[2, 0, 1],
[0, 4, 0],
[0, 0, 0]])
In [476]: kernel
Out[476]:
array([[1, 1, 1],
[1, 0, 1],
[1, 1, 1]])
In [477]: from scipy.ndimage import convolve
In [478]: c = convolve(a, kernel, mode='constant')
In [479]: c
Out[479]:
array([[3, 3, 2],
[5, 8, 5],
[6, 3, 5],
[4, 4, 4]])
Run Code Online (Sandbox Code Playgroud)
您可以使用切片 和np.sum来计算特定区域的总和:
def getsumofneighbors(matrix, i, j):
region = matrix[max(0, i-1) : i+2,
max(0, j-1) : j+2]
return np.sum(region) - matrix[i, j] # Sum the region and subtract center
Run Code Online (Sandbox Code Playgroud)
请注意,max存在 是因为负起始索引会触发不同的切片。
def sum_neighbors(A, i, j):
rows, columns = A.shape
r0, r1 = max(0, i-1), min(rows-1, i+1)
c0, c1 = max(0, j-1), min(columns-1, j+1)
rs = list({r0, i, r1})
cs = [[c] for c in list({c0, j, c1})]
return A[rs, cs].sum() - A[i, j]
Run Code Online (Sandbox Code Playgroud)
A前后按行切片,前后i按列切片j。求和并减去 , 处的单元格i。j所有其他代码都是为了处理边缘。
import numpy as np
mxn = np.array([[0, 1, 0],
[2, 0, 1],
[0, 4, 0],
[0, 0, 0]])
for i, j in [(0, 0), (1, 0), (1, 1)]:
s = "sum of neigbors for i={} and j={} is {}"
print s.format(i, j, sum_neighbors(mxn, i, j))
sum of neigbors for i=0 and j=0 is 3
sum of neigbors for i=1 and j=0 is 5
sum of neigbors for i=1 and j=1 is 8
Run Code Online (Sandbox Code Playgroud)