stani
stani

Reputation: 111

Create binary array from list of indexes in Python

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

Answers (3)

Jab
Jab

Reputation: 27485

Using a comprehension:

indices = {3,4,7,9}
output = [int(i in indices) for i in range(max(indices)+1)]

Upvotes: 2

Reinderien
Reinderien

Reputation: 15231

Simple list comprehension will do it:

indices = {3, 4, 7, 9}
[i in indices for i in range(10)]

Upvotes: 2

Corralien
Corralien

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

Related Questions