1

Is there any libraries functions (Scipy, Numpy, ?) that can double the array size by duplicating the values ? Like this :

  [[1, 2, 4],        [[1. 1. 2. 2. 4. 4.]
   [5, 6, 2],   ->    [1. 1. 2. 2. 4. 4.]
   [6, 7, 9]]         [5. 5. 6. 6. 2. 2.]
                      [5. 5. 6. 6. 2. 2.]
                      [6. 6. 7. 7. 9. 9.]
                      [6. 6. 7. 7. 9. 9.]]

Or is there a faster way to do this operation ? When the array is very large, it becomes a problem. This is what I have so far.

def double_array(array):
  nbr_rows, nbr_cols = array.shape

  array_new = np.zeros((nbr_rows*2, nbr_cols*2))
  for row in range(nbr_rows):
    for col in range(nbr_cols):
      array_new[row*2,col*2] = array[row,col]
      array_new[row*2+1,col*2] = array[row,col]
      array_new[row*2,col*2+1] = array[row,col]
      array_new[row*2+1,col*2+1] = array[row,col]

  return array_new

array = np.array([[1, 2, 4], [5, 6, 2], [6, 7, 9]])
array_new = double_array(array)
print(array_new)
0

3 Answers 3

3

Based on the comment before, you can try np.repeat, for instance:

array = np.array([[1, 2, 4], [5, 6, 2], [6, 7, 9]])
new_arr = np.repeat(np.repeat(array,2,axis=1), [2]*len(array), axis=0)

print(new_arr.astype(np.float))

Output:

[[1. 1. 2. 2. 4. 4.]
 [1. 1. 2. 2. 4. 4.]
 [5. 5. 6. 6. 2. 2.]
 [5. 5. 6. 6. 2. 2.]
 [6. 6. 7. 7. 9. 9.]
 [6. 6. 7. 7. 9. 9.]]
Sign up to request clarification or add additional context in comments.

1 Comment

Yes ! It speed up the computation by about 4 times on a small array !
1

Using numpy.repeat+numpy.tile:

N,M = 2,2 # rows,cols
out = np.repeat(np.tile(array, N), M).reshape(array.shape[0]*N, -1)

output:

array([[1, 1, 2, 2, 4, 4],
       [1, 1, 2, 2, 4, 4],
       [5, 5, 6, 6, 2, 2],
       [5, 5, 6, 6, 2, 2],
       [6, 6, 7, 7, 9, 9],
       [6, 6, 7, 7, 9, 9]])

3 Comments

This works too ! However, the other answer is faster for my use case.
tile uses repeat
Nice to know, thanks @hpaulj I guess this explains why the two commands have a different behavior (eg. being able to create several dimensions for tile)
1

Just repeat one the second and then first axes:

N = 2
new_arr = a.repeat(N, axis=1).repeat(N, axis=0)

Output:

>>> new_arr
array([[1, 1, 2, 2, 4, 4],
       [1, 1, 2, 2, 4, 4],
       [5, 5, 6, 6, 2, 2],
       [5, 5, 6, 6, 2, 2],
       [6, 6, 7, 7, 9, 9],
       [6, 6, 7, 7, 9, 9]])

1 Comment

This is actually the easiest answer to understand and might even be faster than all the others.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.