2

I have numpy array:

a = [355, 355, 1005, 7005, 7005, 7005]

I like this to be converted into binary matrix without any loop (if possible using a single line of code) like this:

m = [[1, 1, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0], [0, 0, 0, 1, 1, 1]]
0

1 Answer 1

4

The logic is not fully clear, do you want some kind of one-hot encoding?

a = np.array([355, 355, 1005, 7005, 7005, 7005])

m = (a==np.unique(a,)[:,None]).astype(int)

output:

array([[1, 1, 0, 0, 0, 0],
       [0, 0, 1, 0, 0, 0],
       [0, 0, 0, 1, 1, 1]])
Sign up to request clarification or add additional context in comments.

2 Comments

I don't know whether the output of an unordered input array meets the requirements of OP, maybe it needs to return_index.
@MechanicPig I don't know the exact logic (thus my question), but yes, the order can be rearranged depending on the use case

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.