label_binarize classes without losing index number

Viewed 90

I am trying to binarize a target class without losing the index number. However, failed and could not find the corresponding option in sklearn.preprocessing.label_binarize. input y:

index  target
 1      0
 3      0
 21     1
 50     1

code:

y=data['target']
y=label_binarize(y, classes=[0, 1])
y=np.hstack((1-y, y))

output:

    0    1
0   1    0
1   1    0
2   0    1
3   0    1

the output I prefer

    0    1
1   1    0
3   1    0
21   0    1
50   0    1
1 Answers

Scikit-Learn functions accept Pandas dataframe as input, but they return numpy array as result. You should consider this rule while working with dataframes.

Therefore y is a numpy array. However you can make it dataframe again like this:

y = pd.DataFrame(y, index=data.index)  # make it dataframe, and pass data indices
y.head()

Now, y is:

    0   1
1   1   0
3   1   0
21  0   1
50  0   1
Related