【问题标题】:How can I copy each value of an array for a certain number of times (Iteration over rows / column)?如何将数组的每个值复制一定次数(迭代行/列)?
【发布时间】:2022-01-08 16:00:58
【问题描述】:

我想遍历现有数组的每个值。每个值都应该以两种方式(列/行)复制一定次数。我想提高分辨率,可以这么说。

简单的例子来理解我的描述:

array = np.array([[1, 2],[1,2]]) # Factor 3 

结果应该是:

arraynew = np.array([[1,1,1,2,2,2],[1,1,1,2,2,2],[1,1,1,2,2,2]])

除了这个例子,我还得处理一个更大的数组,所以手工是不行的。

【问题讨论】:

标签: python arrays numpy iteration


【解决方案1】:

如果您想将数组放大整数次,可以使用Kroenecker product

import numpy as np

array = np.array([[1, 2],[1,2]]) # Factor 3 
factor = 3

np.kron(array, np.ones((factor, factor)))

# array([[1., 1., 1., 2., 2., 2.],
#        [1., 1., 1., 2., 2., 2.],
#        [1., 1., 1., 2., 2., 2.],
#        [1., 1., 1., 2., 2., 2.],
#        [1., 1., 1., 2., 2., 2.],
#        [1., 1., 1., 2., 2., 2.]])

注意:您可以随意改变 (factor, factor) 元组以通过不同的因素增加暗淡 01,例如设置它(3, 2)

另请参阅np.kron 的文档

如果您想放大非整数次并使用图像,您可能希望使用插值缩放,例如 scipy.misc.imresize

【讨论】:

  • 非常好的答案!
【解决方案2】:
a = [1, 2]

factor = 3

def solv_the_problem(factor):
    x=[]
    y = []
    for i in a:
        for _ in range(0, factor):
            x.append(i)

    for _ in range(0, factor):
        y.append(x)

    return y

vector = solv_the_problem(factor)
print(vector)

【讨论】:

    猜你喜欢
    • 2020-11-28
    • 1970-01-01
    • 1970-01-01
    • 2021-02-27
    • 2019-03-19
    • 2021-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多