Home > Blockchain >  How can I copy each value of an array for a certain number of times (Iteration over rows / column)?
How can I copy each value of an array for a certain number of times (Iteration over rows / column)?

Time:01-09

I want to iterate through each value of my existing array. Each value should be copied in both ways (column/row) for a certain number of times. I want to increase the resolution, so to speak.

Simple example to understand my description:

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

Result should be:

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

Besides this example, I have to work with a bigger array, so it's not doable by hand.

CodePudding user response:

You can use the Kroenecker product if you would like to up-scale your array an integer number of times.

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.]])

Note: You are free to vary the (factor, factor) tuple to increase dim 0 and 1 by different factors, e.g. set it (3, 2).

See also the docs for np.kron

If you would like to upscale a non-integer number of times and are using images, you likely want to use scaling with interpolation e.g scipy.misc.imresize.

CodePudding user response:

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)
  •  Tags:  
  • Related