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)
CodePudding user response:
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.]]
CodePudding user response:
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]])
CodePudding user response:
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]])