python - 通过最近邻平铺对 numpy 数组进行上采样的快速方法

标签 python arrays numpy

<分区>

我有一个 MxN 的二维整数数组,我想将该数组扩展为 (BM)x(BN),其中 B 是方 block 边的长度,因此输入数组的每个元素在最终数组中重复为 BxB block 。下面是一个带有嵌套 for 循环的示例。有没有更快/内置的方法?

import numpy as np

a = np.arange(9).reshape([3,3])            # input array - 3x3
B=2.                                       # block size - 2  
A = np.zeros([a.shape[0]*B,a.shape[1]*B])  # output array - 6x6

# Loop, filling A with tiled values of a at each index
for i,l in enumerate(a):                   # lines in a
    for j,aij in enumerate(l):             # a[i,j]
        A[B*i:B*(i+1),B*j:B*(j+1)] = aij

结果...

a=      [[0 1 2]
         [3 4 5]
         [6 7 8]]

A =     [[ 0.  0.  1.  1.  2.  2.]
         [ 0.  0.  1.  1.  2.  2.]
         [ 3.  3.  4.  4.  5.  5.]
         [ 3.  3.  4.  4.  5.  5.]
         [ 6.  6.  7.  7.  8.  8.]
         [ 6.  6.  7.  7.  8.  8.]]

最佳答案

一个选项是

>>> a.repeat(2, axis=0).repeat(2, axis=1)
array([[0, 0, 1, 1, 2, 2],
       [0, 0, 1, 1, 2, 2],
       [3, 3, 4, 4, 5, 5],
       [3, 3, 4, 4, 5, 5],
       [6, 6, 7, 7, 8, 8],
       [6, 6, 7, 7, 8, 8]])

由于中间数组,这有点浪费,但至少很简洁。

关于python - 通过最近邻平铺对 numpy 数组进行上采样的快速方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32846846/

相关文章:

python - 如何在 python 中将 UTC-4 转换为美国/东部时间?

python - Apache Web 服务器上的 Django 'dict' 对象没有属性 'render_context'

python - 用较小的数组替换较大的 numpy 数组中的值

random - numpy中的非重复随机数

python - 赛通: "fatal error: numpy/arrayobject.h: No such file or directory"

java - 使用多种编程语言(Python Java C#)构建用于开发 Web 应用程序的基础架构

python - 从两个数组创建所有可能的组合

javascript - 如何检查用户输入数组是否等于特定对象?

c# - 运算符不能应用于类型为 'Method Group' 和 'int' 的操作数

javascript - 按字符串数组过滤javascript数组