1

Given 2d array k = np.zeros((M, N)) and list of indices in the range 0, 1 .., M-1 of size N called places = np.random.random_integers(0, M-1, N) how do I assign 1 in each column of k in the places[i] index where i is running index. I would like to achieve that in python compact style and without any loops

Examples:

N = 5, M =3
places= 0, 0, 1, 1, 2

Then:

k = [1, 1, 0, 0, 0
     0, 0, 1, 1, 0
     0, 0, 0, 0, 1]

1 Answer 1

1
rslt = np.zeros((M, N))
for i, v in enumerate(places): rslt[v,i]=1

Full code:

import numpy as np
N = 5
M=3
#places = np.random.random_integers(0, M-1, N)
places= 0, 0, 1, 1, 2
rslt = np.zeros((M, N))
for i, v in enumerate(places): rslt[v,i]=1
print(rslt)

Out [34]:
[[ 1.  1.  0.  0.  0.]
 [ 0.  0.  1.  1.  0.]
 [ 0.  0.  0.  0.  1.]]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.