Ning
Ning

Reputation: 595

Python - how to resize an array and duplicate the elements

I've got an array with data like this

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

and I want to change it to

b = [[1,1,2,2,3,3],[1,1,2,2,3,3],[4,4,5,5,6,6],[4,4,5,5,6,6],[7,7,8,8,9,9],[7,7,8,8,9,9]]

I've tried to use numpy.resize() function but after resizing, it gives [[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]. I can use a for loop to put the numbers at the indexes I need but just wondering if there is any easier way of doing that?

To visualise the task, here is the original array

Array a

This is what I want

Array b

Upvotes: 3

Views: 1347

Answers (2)

MisterMiyagi
MisterMiyagi

Reputation: 52169

You can think of your problem as resizing each 1x1 block to a 2x2 block. This can simply be done using numpy.kron(a, b), which operates on each element of a – each 1x1 block – and "expands" it according to b – which should thus be a 2x2 block.

>>> import numpy as np
>>> a = np.array([[1,2,3],[4,5,6],[7,8,9]])
>>> np.kron(a, [[1, 1], [1, 1]])
array([[1, 1, 2, 2, 3, 3],
       [1, 1, 2, 2, 3, 3],
       [4, 4, 5, 5, 6, 6],
       [4, 4, 5, 5, 6, 6],
       [7, 7, 8, 8, 9, 9],
       [7, 7, 8, 8, 9, 9]])

An efficient way to create the second operand for larger structures is using np.ones and related functions.

>>> np.kron(a, np.ones((2,4), dtype=int))
array([[1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3],
       [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3],
       [4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6],
       [4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6],
       [7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9],
       [7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9]])

Upvotes: 1

Modularizer
Modularizer

Reputation: 651

My initial though was that np.tile would work but in fact what you are looking for is np.repeat twice on two different axes.

Try this runnable example!

#!/usr/bin/env python

import numpy as np
a = [[1,2,3],[4,5,6],[7,8,9]]
b = np.repeat(np.repeat(a, 2, axis=1), 2, axis=0)
b
<script src="https://modularizer.github.io/pyprez/pyprez.min.js"></script>

Upvotes: 5

Related Questions