我有一个看起来像这样的矩阵:
[[ 0 0 0 0 ]
[ 0 0 0 0 ]
[ 0 1 0 0 ]
[ 0 0 0 0 ]
[ 0 0 0 0 ]
[ 0 0 0 0 ]
[ 0 0 0 0 ]
[ 0 0 0 0 ]
[ 0 0 0 0 ]
[ 0 0 1 0 ]
[ 0 0 0 0 ]]
我希望以某种方式更改它,如果一行中有1
值,那么在1
之上和之后也要生成两行,因此输出应为:< / p>
[[ 0 1 0 0 ]
[ 0 1 0 0 ]
[ 0 1 0 0 ]
[ 0 1 0 0 ]
[ 0 1 0 0 ]
[ 0 0 0 0 ]
[ 0 0 0 0 ]
[ 0 0 1 0 ]
[ 0 0 1 0 ]
[ 0 0 1 0 ]
[ 0 0 1 0 ]]
有任何想法或帮助吗?
谢谢
答案 0 :(得分:1)
for (x,y) in np.argwhere(n==1):
xfrom=max(x-2,0)
xto=min(n.shape[0]-1,x+2)
for i in range(xfrom, xto+1):
n[i,y]=1
答案 1 :(得分:0)
在处理0和1的数组时,您可能希望将其转换为布尔数组并使用逻辑运算符。并且,在numpy中切片和索引非常方便。
def expand_in_place(bool_matrix, expand_up=2, expand_down=2):
assert expand_up >= 0 and expand_down >= 0
# expands upward
for _ in range(expand_up):
bool_matrix[:-1] |= bool_matrix[1:].copy()
# expands downward
for _ in range(expand_down):
bool_matrix[1:] |= bool_matrix[:-1].copy()
matrix = np.array([[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 0]])
bool_matrix = matrix.astype(bool)
expand_in_place(bool_matrix)
print() # newline
print(bool_matrix.astype(int))
输出:
In [64]:
[[0 1 0 0]
[0 1 0 0]
[0 1 0 0]
[0 1 0 0]
[0 1 0 0]
[0 0 0 0]
[0 0 0 0]
[0 0 1 0]
[0 0 1 0]
[0 0 1 0]
[0 0 1 0]]
bool_matrix[:-1] |= bool_matrix[1:]
时会发生什么。我添加了.copy()
,因为bool_matrix[1:] |= bool_matrix[:-1]
无效。
In [108]: small = np.array([False, False, True, False, False])
In [109]: small[1:] |= small[:-1]
In [110]: small
Out[110]:
array([False, False, True, True, True], dtype=bool)
答案 2 :(得分:0)
更容易:
for row, col in np.argwhere(n == 1):
n[row-2:row+3,col] = 1
让Python和NumPy的切片语义为你工作。无需计算边界。