python - 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]
解决方案
您可以通过以下方式完成任务:
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块中的两个版本)。
推荐阅读
- sql - 查询和分组多个列属性,例如具有许多作者的书籍
- c# - Xamarin Firebase 如何将没有密钥的单个子记录读入 .AsObservable .Subscribe 快照
- javascript - 是否可以获取与给定 Microsoft 团队用户的对话 ID
- python-3.x - 从列表中修剪数据以适合特定形状,例如地理数据框地图
- javascript - 如何在 useEffect 挂钩中使用 Const 中的变量?反应 JS
- javascript - Jest spyOn 仅在第二次调用和第三次调用时模拟实现
- sql - ComboBox 不接受所选项目的 Null
- javascript - 如何在 dynamodb 的嵌套元素中执行 updateItem?
- java - 应用程序在访问 RecyclerView 时崩溃
- python - 需要根据单元格值更新 pandas 数据框行。此外,如果 2 行具有相同的单元格值,则只需更新第一行