Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I duplicate the values for the last dimension in a numpy array?

Tags:

python

numpy

I am getting an error in numpy when I perform the pairwise multiplication of two arrays a and b since a has dimensions 100 x 200 x 3, while b has dimensions 100 x 200. However, b contains only 0s and 1s. How do I repeat the last dimension of b 3 times to turn b into a 100 x 200 x 3 array?

This is something akin to repmat in matlab. I basically want to triplicate the last dimension of b. I've tried np.tile(b, (1, 1, 3)), but that yields the wrong dimensions.

like image 884
dangerChihuahua007 Avatar asked Sep 18 '25 01:09

dangerChihuahua007


1 Answers

a * b[..., np.newaxis]

Give b another length-1 axis on the end, and broadcasting will handle this for you without needing to actually construct a tripled array.

like image 61
user2357112 supports Monica Avatar answered Sep 20 '25 16:09

user2357112 supports Monica