简体   繁体   中英

building a 3d Numpy array from a 2d numpy array

So I've got a numpy array like this:

a = np.array([[1, 2, 3],
              [2, 3, 4],
              [4, 5, 6]])

and I want to convert it into an array like this:

[[[1, 1, 1], [2, 2, 2], [3, 3, 3]],
 [[2, 2, 2], [3, 3, 3], [4, 4, 4]],
 [[4, 4, 4], [5, 5, 5], [6, 6, 6]]]

How would you do it?

Use numpy.repeat on the array with one extra dimension:

np.repeat(a[...,None], 3, axis=2)

Or numpy.tile :

np.tile(a[...,None], (1,1,3))

Output:

array([[[1, 1, 1],
        [2, 2, 2],
        [3, 3, 3]],

       [[2, 2, 2],
        [3, 3, 3],
        [4, 4, 4]],

       [[4, 4, 4],
        [5, 5, 5],
        [6, 6, 6]]])

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM