Allen
Allen

Reputation: 427

Create an array according to index in another array in Python

I have an array like this:

X= [[1,2,3],
    [3,2,1],
    [2,1,3]]

Now I want to create another array Y. The elements in Y should take value 1 at positions where elements in X equal 2, otherwise they should take value 0. In this example, Y should equal to

Y=[[0,1,0],
   [0,1,0],
   [1,0,0]]

Upvotes: 1

Views: 4226

Answers (3)

enumaris
enumaris

Reputation: 1938

Y = [[1 if i==2 else 0 for i in row] for row in X]

Upvotes: 3

sacuL
sacuL

Reputation: 51335

This would be greatly facilitated (and sped up) by using numpy:

import numpy as np

Y = (np.array(X) == 2).astype(int)

>>> Y
array([[0, 1, 0],
       [0, 1, 0],
       [1, 0, 0]])

Upvotes: 5

blhsing
blhsing

Reputation: 106465

You can use a list comprehension like this:

Y = [[int(i == 2) for i in l] for l in X]

Upvotes: 4

Related Questions