Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 244
Ning Avatar asked Jan 24 '26 23:01

Ning


1 Answers

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>
like image 142
Modularizer Avatar answered Jan 26 '26 12:01

Modularizer