5

I'm trying to copy every element into a 2d array in Python such that it doubles the size of the array and adds the element directly after the element that it intends to copy.

For example:

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

becomes

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

Can anyone help with this problem? Thanks!

horizon516
  • 53
  • 1
  • 3

1 Answers1

6

You can use np.repeat(..) [numpy-doc] for this:

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

We thus repeat, for the second axis (axis=1) the elements two times.

We can also use list-comprehension, but given that the data has the same time, using numpy is faster, and more declarative:

times2 = [[xi for x in row for xi in [x, x]] for row in a]

This the produces:

>>> [[xi for x in row for xi in [x, x]] for row in a]
[[1, 1, 2, 2, 3, 3], [4, 4, 5, 5, 6, 6], [7, 7, 8, 8, 9, 9]]
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555