arr = [[1 0 0]    # 3x3
       [0 1 0]
       [0 0 1]]

largeArr = [[1 1 0 0 0 0]   # 6x6
            [1 1 0 0 0 0]
            [0 0 1 1 0 0]
            [0 0 1 1 0 0]
            [0 0 0 0 1 1]
            [0 0 0 0 1 1]]

如上所述,我希望保留相同的"网格"格式,同时增加2D数组的尺寸.我该怎么做呢?我假设原始矩阵只能按整数n放大.

推荐答案

如果performance很重要(similar post),则可以使用numba,而不需要python jitting,如果需要,可以使用并行模式(通过一些优化可以更快地编写此代码):

@nb.njit      # @nb.njit("int64[:, ::1](int64[:, ::1], int64)", parallel =True)
def numba_(arr, n):
    res = np.empty((arr.shape[0] * n, arr.shape[0] * n), dtype=np.int64)
    for i in range(arr.shape[0]):     # for i in nb.prange(arr.shape[0])
        for j in range(arr.shape[0]):
            res[n * i: n * (i + 1), n * j: n * (j + 1)] = arr[i, j]
    return res

例如:

arr = [[0 0 0 1 1]
       [0 1 1 1 1]
       [1 1 0 0 1]
       [0 0 1 0 1]
       [0 1 1 0 1]]

res (n=3):
[[0 0 0 0 0 0 0 0 0 1 1 1 1 1 1]
 [0 0 0 0 0 0 0 0 0 1 1 1 1 1 1]
 [0 0 0 0 0 0 0 0 0 1 1 1 1 1 1]
 [0 0 0 1 1 1 1 1 1 1 1 1 1 1 1]
 [0 0 0 1 1 1 1 1 1 1 1 1 1 1 1]
 [0 0 0 1 1 1 1 1 1 1 1 1 1 1 1]
 [1 1 1 1 1 1 0 0 0 0 0 0 1 1 1]
 [1 1 1 1 1 1 0 0 0 0 0 0 1 1 1]
 [1 1 1 1 1 1 0 0 0 0 0 0 1 1 1]
 [0 0 0 0 0 0 1 1 1 0 0 0 1 1 1]
 [0 0 0 0 0 0 1 1 1 0 0 0 1 1 1]
 [0 0 0 0 0 0 1 1 1 0 0 0 1 1 1]
 [0 0 0 1 1 1 1 1 1 0 0 0 1 1 1]
 [0 0 0 1 1 1 1 1 1 0 0 0 1 1 1]
 [0 0 0 1 1 1 1 1 1 0 0 0 1 1 1]]

Performances (perfplot)

在我的基准测试中,numba将是最快的(对于大型n,并行模式将更好),之后BrokenBenchmark answer将比scipy.ndimage.zoom快.在基准测试中,farr.shape[0]n是重复计数:

enter image description here

Python相关问答推荐

try 从网站获取表(ValueRight:如果使用所有纯量值,则必须传递索引)

在有限数量的唯一字母的长字符串中,找到包含重复不超过k次的所有唯一字母的最长子字符串

无法获得指数曲线_fit来处理日期

两极:滚动组,起始指数由不同列设置

FastAPI:使用APIRouter路由子模块功能

Flask:如何在完整路由代码执行之前返回验证

KNN分类器中的GridSearchCV

pandas DataFrame中类型转换混乱

在Pandas框架中截短至固定数量的列

如何计算列表列行之间的公共元素

使用scipy. optimate.least_squares()用可变数量的参数匹配两条曲线

三个给定的坐标可以是矩形的点吗

使用新的类型语法正确注释ParamSecdecorator (3.12)

如何比较numPy数组中的两个图像以获取它们不同的像素

非常奇怪:tzLocal.get_Localzone()基于python3别名的不同输出?

通过Selenium从页面获取所有H2元素

从numpy数组和参数创建收件箱

如果条件不满足,我如何获得掩码的第一个索引并获得None?

如何从pandas的rame类继承并使用filepath实例化

搜索按钮不工作,Python tkinter