1

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]]
1
  • 4
    What did you try and what didn't work? Commented Dec 10, 2018 at 22:46

3 Answers 3

5

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]])
Sign up to request clarification or add additional context in comments.

Comments

4

You can use a list comprehension like this:

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

1 Comment

Thanks. It works, though a bit slow compared with using the numpy module.
3
Y = [[1 if i==2 else 0 for i in row] for row in X]

3 Comments

You have it backwards
Should be 1 if ... else 0
Yes, sorry I had the numbers backwards. Thanks for the reminder.

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.