Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to copy numpy array value into higher dimensions

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?

like image 758
user1871528 Avatar asked Sep 13 '16 05:09

user1871528


People also ask

How do I increase the dimensions of a NumPy array?

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 ).

How do I copy a NumPy array to another variable?

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.

How do you copy an array in NumPy?

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.

Can NumPy arrays have more than 2 dimensions?

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.


2 Answers

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)
like image 186
Divakar Avatar answered Sep 28 '22 10:09

Divakar


Another approach that works:

x_train = np.stack((x_train,) * 3, axis=-1)

like image 20
liamzebedee Avatar answered Sep 28 '22 10:09

liamzebedee