Conrado Ermel
Conrado Ermel

Reputation: 21

duplicating last column of 3d numpy array

I have the following numpy 3d array, in which I need to duplicate the last column

array([[[ 7, 5, 93],
        [19, 4, 69],
        [62, 2, 52]],

       [[ 6, 1, 65],
        [41, 9, 94],
        [39, 4, 49]]])

The desired output is:

array([[[ 7, 5, 93, 93],
        [19, 4, 69, 69],
        [62, 2, 52, 52]],

       [[ 6, 1, 65, 65],
        [41, 9, 94, 94],
        [39, 4, 49, 49]]])

Is there a clever way of doing this?

Upvotes: 2

Views: 127

Answers (2)

Ehsan
Ehsan

Reputation: 12397

There is a built-in numpy function for this purpose:

np.insert(x,-1,x[...,-1],-1)

output:

array([[[ 7,  5, 93, 93],
        [19,  4, 69, 69],
        [62,  2, 52, 52]],

       [[ 6,  1, 65, 65],
        [41,  9, 94, 94],
        [39,  4, 49, 49]]])

Upvotes: 1

Umang Gupta
Umang Gupta

Reputation: 16440

You could concatenate along the last axis as follows-

numpy.concatenate([a, numpy.expand_dims(a[:, :, -1], axis=2)], axis=2)

Upvotes: 2

Related Questions