Chris
Chris

Reputation: 31206

Numpy: set all values of a matrix to the right of the maximal value in each row to the maximal value in that row

Basically, I am looking for the numpy primitives which will accomplish the following for loop impementation:

# for a matrix M
argmaxes = np.argmax(M,axis=1)

for i,arg in enumerate(argmaxes):
  M[i,arg:] = M[i,arg]

Is there a numpy-ish way to accomplish this?

Upvotes: 1

Views: 31

Answers (1)

Quang Hoang
Quang Hoang

Reputation: 150745

The following doesn't use for loop, but it creates several intermediate arrays of the same shape as M. So I'm not sure how efficient it is over loop:

maxes = np.max(M, axis=1)

M = np.where(np.arange(M.shape[1]) > argmaxes[:,None],
         maxes[:,None], 
         M)

Upvotes: 2

Related Questions