python - Assigning 2d array in vector of indices -
given 2d array k = np.zeros((m, n))
, list of indices in range 0, 1 .., m-1
of size n
called places = np.random.random_integers(0, m-1, n)
how assign 1 in each column of k
in places[i]
index running index. achieve in python compact style , without 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]
rslt = np.zeros((m, n)) i, v in enumerate(places): rslt[v,i]=1
full code:
import numpy 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)) 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.]]
Comments
Post a Comment