Reputation: 111
I have a list of indexes, say [3,4,7,9]. What is the fastest way to create a binary array (in this case [0,0,0,1,1,0,0,1,0,1]). Thanks!
Upvotes: 0
Views: 1924
Reputation: 27485
Using a comprehension:
indices = {3,4,7,9}
output = [int(i in indices) for i in range(max(indices)+1)]
Upvotes: 2
Reputation: 15231
Simple list comprehension will do it:
indices = {3, 4, 7, 9}
[i in indices for i in range(10)]
Upvotes: 2
Reputation: 120409
With numpy:
l = [3,4,7,9]
m = np.zeros(max(l)+1)
m[l] = 1
>>> m
array([0., 0., 0., 1., 1., 0., 0., 1., 0., 1.])
Upvotes: 3