0

I'm imagining something like this:

import numpy as np

a = np.arange(12).reshape(4,3)
rows = np.asarray([1,2,3])
cols = np.argmax(a[rows], axis=1)
indices = np.stack((rows, cols)).T
a[indices] = 1

The desired output for a would then be

[[ 0  1  2]
 [ 3  4  1]
 [ 6  7  1]
 [ 9 10  1]]

However, this doesn't work and doesn't change a. How does it work?

3
  • 2
    And what is b? Commented Sep 13, 2019 at 8:15
  • Oops sorry, I forgot to rename it, too. Commented Sep 13, 2019 at 8:20
  • 1
    a[rows,cols] = 1? Commented Sep 13, 2019 at 8:21

2 Answers 2

3

You are almost there. Change the penultimate line:

import numpy as np

a = np.arange(12).reshape(4,3)
rows = np.asarray([1,2,3])
cols = np.argmax(a[rows], axis=1)
a[rows, cols] = 1
Sign up to request clarification or add additional context in comments.

Comments

1

You can use multidimensional "fancy indexing":

import numpy as np

a = np.arange(12).reshape(4,3)
rows = np.asarray([1,2,3])
cols = np.argmax(a[rows], axis=1)
indices = np.stack((rows, cols)).T
a[rows, cols] = 1

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.