f. c.
f. c.

Reputation: 1135

How to keep the dimensions when using the basic arithmetic operations with Numpy

Recently I encounter a dimension problem and has to reshape the array after each calculation. For example,

a=np.random.rand(2,3,4)
t=2
b=a[:,1,:] + a[:,2,:]*t

The second axis of a is reduced automatically and b becomes a 2x4 array. How to keep the shape of b to be [2,1,4]. In numpy.sum(), we can set keepdims=True, but for the basic arithmetic operations, how to do it?

Upvotes: 2

Views: 84

Answers (1)

Convert the integer indies into lists:

>>> b = a[:,[1],:] + a[:,[2],:]*t
>>> b.shape
(2, 1, 4)

Upvotes: 1

Related Questions