I have an np.array
with several labels, let's say label1
, ..., label10
.
Given a specific label, let's say label1
. I want to turn it to a binary vector where y'[j] == 1
iff y[j] == label1
How to do that?
CodePudding user response:
Alright, I found a fine way:
import numpy as np
label = 'label1'
tobinary = lambda val: 1 if val == label else 0
vfunc = np.vectorize(tobinary)
vfunc(y)
relying on this SO answer
CodePudding user response:
Simple comparison:
>>> np.array([f'label{i}' for i in range(10)])
array(['label0', 'label1', 'label2', 'label3', 'label4', 'label5',
'label6', 'label7', 'label8', 'label9'], dtype='<U6')
>>> ar = np.array([f'label{i}' for i in range(10)])
>>> ar == 'label1'
array([False, True, False, False, False, False, False, False, False,
False])
If you want a binary vector:
>>> (ar == 'label1').astype(int)
array([0, 1, 0, 0, 0, 0, 0, 0, 0, 0])