assigning to multi-dimensional array

Sammy

i have a 3d array of zeros and i want to fill it with a 1d array:

In [136]: C = np.zeros((3,5,6),dtype=int)

In [137]: C
Out[137]: 
array([[[0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0]],

       [[0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0]],

       [[0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0]]])

In [138]: s
Out[138]: array([10, 20, 30, 40, 50])

I want to achieve this: (without using a loop)

array([[[10, 10, 10, 10, 10, 10],
        [20, 20, 20, 20, 20, 20],
        [30, 30, 30, 30, 30, 30],
        [40, 40, 40, 40, 40, 40],
        [50, 50, 50, 50, 50, 50]],

       [[10, 10, 10, 10, 10, 10],
        [20, 20, 20, 20, 20, 20],
        [30, 30, 30, 30, 30, 30],
        [40, 40, 40, 40, 40, 40],
        [50, 50, 50, 50, 50, 50]],

       [[10, 10, 10, 10, 10, 10],
        [20, 20, 20, 20, 20, 20],
        [30, 30, 30, 30, 30, 30],
        [40, 40, 40, 40, 40, 40],
        [50, 50, 50, 50, 50, 50]]])

by assigning s to each column of each ith element.

note I can easily get something similar:

array([[[10, 20, 30, 40, 50, 60],
        [10, 20, 30, 40, 50, 60],
        [10, 20, 30, 40, 50, 60],
        [10, 20, 30, 40, 50, 60],
        [10, 20, 30, 40, 50, 60]],

       [[10, 20, 30, 40, 50, 60],
        [10, 20, 30, 40, 50, 60],
        [10, 20, 30, 40, 50, 60],
        [10, 20, 30, 40, 50, 60],
        [10, 20, 30, 40, 50, 60]],

       [[10, 20, 30, 40, 50, 60],
        [10, 20, 30, 40, 50, 60],
        [10, 20, 30, 40, 50, 60],
        [10, 20, 30, 40, 50, 60],
        [10, 20, 30, 40, 50, 60]]])

By :

 C[:,:,:] = s

But can't see how to assign s to j for all i and k in [i,j,k]

it seems numpy prioritises the last colon C[:,:,:]. is there a nice way around this?

Viktor Kerkez
tmp = C.swapaxes(1, 2)
tmp[:] = s
C = tmp.swapaxes(1, 2)

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related