Issue
I have an array of array( [1,2,3, 4, 1,2 ,3 ,3,3,3]) having shape (10,)
a = np.array([1,2,3, 4, 1,2 ,3 ,3,3,3])
print(a)
print(a.shape)
which has unique values 1,2,3,4 ie m = 4, unique values. Actual data i quite large nad has nuniuqe of ~300 How to pivot it to get an array of shape (10,4)
Expected output
array([[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1],
[1, 0, 0, 0],
...,
[0, 0, `, 0]])
Solution
Using broadcasting comparison:
out = (a[:,None] == np.unique(a)).astype(int)
output:
array([[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1],
[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 1, 0],
[0, 0, 1, 0],
[0, 0, 1, 0]])
alternative
If you want to ensure having empty columns on missing numbers:
out = (a[:,None] == np.arange(a.max())+1).astype(int)
To see the difference, let's use a = np.array([1,3,5,3,1])
as input:
a = np.array([1,3,5,3,1])
array([1, 3, 5, 3, 1])
(a[:,None] == np.unique(a)).astype(int)
# 1 3 5
array([[1, 0, 0],
[0, 1, 0],
[0, 0, 1],
[0, 1, 0],
[1, 0, 0]])
(a[:,None] == np.arange(a.max())+1).astype(int)
# 1 2 3 4 5
array([[1, 0, 0, 0, 0],
[0, 0, 1, 0, 0],
[0, 0, 0, 0, 1],
[0, 0, 1, 0, 0],
[1, 0, 0, 0, 0]])
Answered By - mozway
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.