I have a single 2D array that I want to stack identical versions of into a third dimension, specifically axis=1
. The following code does the job, but it's very slow for a 2D array of size (300,300)
stacked into a third-dimension of length 300.
arr_2d = arr_2d.reshape(arr_2d.shape[0],arr_2d.shape[1],1)
arr_3d = np.empty((sampling,sampling,sampling)) # allocate space
arr_3d = [arr_3d[:,:,i]==arr_2d for i in range(sampling)]
Is there a better, more efficient way of doing this?
You can use numpy.repeat after you add a new third dimension to stack on:
import numpy as np
arr = np.random.rand(300, 300)
# arr.shape => (300, 300)
dup_arr = np.repeat(arr.reshape(*arr.shape, 1), repeats=10, axis=-1)
# dup_arr.shape => (300, 300, 10)
As commented by @xdurch0 and since you're stacking your copies along the last dimension, you can also use numpy.tile:
dup_arr = np.tile(arr.reshape(*arr.shape, 1), reps=10)
# dup_arr.shape => (300, 300, 10)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.