简体   繁体   中英

How to make (z,x,y,1)-shape numpy array into (z,x,y,3)-shape numpy array by duplicating the last element 3 times?

I want to make (z,x,y,1) -shaped numpy array into (z,x,y,3) -shaped numpy array by duplicating the last element?

For example given

import numpy as np
# The shape is (1,2,2,1) (that is z=1, x=2, y=2)
a = np.array([[[[1], [2]],[[3], [4]]]])
print(a.shape) 

# I want to make it (1,2,2,3) by duplicating the last element 3 times as follow
a = np.array([[[[1,1,1], [2,2,2]],[[3,3,3], [4,4,4]]]]) 
print(a.shape)

so given a numpy array a of shape (z,x,y,1) , how to make it (z,x,y,3) numpy array by duplicating the last element?

Try this:

def repeat_last(a, n=3):
    a.repeat(n, axis=2).reshape(*a.shape[:-1], n)

You can use np.broadcast_to to do explicit broadcasting.

assert(a.shape[-1] == 1)  # check it really is 1 in the last dimension

new_shape = a.shape[:-1] + (3,)

np.broadcast_to(a, new_shape)

You can concatenate three arrays (which are all a ) along the last axis:

np.concatenate([a]*3, axis=-1)

NumPy's tile will do the trick. You just have to indicate the number of repetitions of the array along each axis (parameter reps ).

In [39]: import numpy as np

In [40]: a = np.array([[[[1], [2]], [[3], [4]]]])

In [41]: b = np.array([[[[1,1,1], [2,2,2]], [[3,3,3], [4,4,4]]]]) 

In [42]: c = np.tile(a, (1, 1, 1, 3))

In [43]: np.array_equal(b, c)
Out[43]: True

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