Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Double array by duplicating values in Python

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.]]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading