Home > Software engineering >  Python - how to resize an array and duplicate the elements
Python - how to resize an array and duplicate the elements

Time:10-25

I've got an array like this a = [[1,2,3],[4,5,6],[7,8,9]], and I want to change it tob = [[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?

Here is the original array Array a

This is what I want Array b

CodePudding user response:

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>

  • Related