I have a (w,h) np array in 2d. I want to make a 3d dimension that has a value greater than 1 and copy its value over along the 3rd dimensions. I was hoping broadcast would do it but it can't. This is how i'm doing it
arr = np.expand_dims(arr, axis=2)
arr = np.concatenate((arr,arr,arr), axis=2)
is there a a faster way to do so?
To add new dimensions (increase dimensions) to the NumPy array ndarray , you can use np. newaxis , np. expand_dims() and np. reshape() (or reshape() method of ndarray ).
Conclusion: to copy data from a numpy array to another use one of the built-in numpy functions numpy. array(src) or numpy. copyto(dst, src) wherever possible.
Python Numpy – Duplicate or Copy Array Copying array means, a new instance is created, and the contents of the original array is copied into this array. To copy array data to another using Python Numpy library, you can use numpy. ndarray. copy() function.
Creating arrays with more than one dimension In general numpy arrays can have more than one dimension. One way to create such array is to start with a 1-dimensional array and use the numpy reshape() function that rearranges elements of that array into a new shape.
You can push all dims forward, introducing a singleton dim/new axis as the last dim to create a 3D
array and then repeat three times along that one with np.repeat
, like so -
arr3D = np.repeat(arr[...,None],3,axis=2)
Here's another approach using np.tile
-
arr3D = np.tile(arr[...,None],3)
Another approach that works:
x_train = np.stack((x_train,) * 3, axis=-1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With