首页 > 解决方案 > How to draw plus sign (+) into n*n numpy zero array

问题描述

How we can replace elements of a NumPy array of size (n*n) if we have np.zeros array and need to replace it with 1's so that shape looks like '+' such that 1's must be present at the middle row and column.

import numpy as np
x = np.zeros(5*5).reshape(5,5)
x[2:3,2:3] = 1

output:

 [0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0.]
 [0. 0. 1. 0. 0.]
 [0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0.]

but expected is:

   [0, 0, 1, 0, 0],
   [0, 0, 1, 0, 0],
   [1, 1, 1, 1, 1],
   [0, 0, 1, 0, 0],
   [0, 0, 1, 0, 0]

标签: pythonarraysnumpy

解决方案


您可以通过以下方式完成任务:

n = x.shape[0] // 2
x[n, n-1:n+2] = 1
x[n-1:n+2, n] = 1

我创建了传递dtype='int'的数组并得到:

array([[0, 0, 0, 0, 0],
       [0, 0, 1, 0, 0],
       [0, 1, 1, 1, 0],
       [0, 0, 1, 0, 0],
       [0, 0, 0, 0, 0]])

(整数)。

或者,如果您想在中间列和行的所有元素中包含1 ,请运行:

x[n, :] = 1
x[:, n] = 1

这次你会得到:

array([[0, 0, 1, 0, 0],
       [0, 0, 1, 0, 0],
       [1, 1, 1, 1, 1],
       [0, 0, 1, 0, 0],
       [0, 0, 1, 0, 0]])

按照关于偶数数组的评论进行编辑

对于偶数大小的数组,您可以使用相同的代码,但这次“十字”并不完全位于中间。

例如,如果数组是6 * 6,则结果是:

array([[0, 0, 0, 1, 0, 0],
       [0, 0, 0, 1, 0, 0],
       [0, 0, 0, 1, 0, 0],
       [1, 1, 1, 1, 1, 1],
       [0, 0, 0, 1, 0, 0],
       [0, 0, 0, 1, 0, 0]])

或者,如果您接受“双”宽度的交叉(2 个中间行和列),您可以运行:

n = x.shape[0] // 2
x[n-1:n, :] = 1
x[:, n-1:n] = 1

这一次的结果将是:

array([[0, 0, 1, 1, 0, 0],
       [0, 0, 1, 1, 0, 0],
       [1, 1, 1, 1, 1, 1],
       [1, 1, 1, 1, 1, 1],
       [0, 0, 1, 1, 0, 0],
       [0, 0, 1, 1, 0, 0]])

如果您事先不知道数组的形状,则必须检查行数是偶数还是奇数,然后运行我的代码的合适版本(if / else块中的两个版本)。


推荐阅读