The following is a real-world problem in numPy
reduced to the essentials, just with smaller dimensions.
Let's say I want to create an n-dimensional array all
with dimensions (10, 10, 100):
all = np.empty((10, 10, 100))
I also have a 1d array data
, simulated here as
data = np.arange(0, 100)
for all i, j I now want to achieve that
all[i,j]=data
So I do:
all[:, :]=data
Of course that works.
But now I want to import data
to all2
with shape (100, 10, 10). I could do that with
all2 = np.empty((100, 10, 10)) # new target to be populated
for i in range(100):
for j in range(10):
for k in range(10):
all2[i, j, k]=data[i]
But is there an easier way to do this without looping? I would be surprised if it couldn't be done more elegantly, but I don't see how.
You can use transpose: all2.T[:] = data
(note the second , :
insn't necessary)