As a working example modified from here, say I have
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.preprocessing import OneHotEncoder
X = pd.DataFrame(
{'type': ['type1', 'type1', 'type1', 'type1', 'type2', 'type2', 'type2', 'type3', 'type3', 'type4'],
'feat': ['A','B','C','D','A','B','C','A','B','A']})
column_trans = ColumnTransformer(
[('type_', OneHotEncoder(),['type']),
('feate_', OneHotEncoder(),['feat'])],
remainder='drop')
column_trans.fit(X)
column_trans.get_feature_names()
column_trans.transform(X).toarray()
which will output
array([[1., 0., 0., 0., 1., 0., 0., 0.],
[1., 0., 0., 0., 0., 1., 0., 0.],
[1., 0., 0., 0., 0., 0., 1., 0.],
[1., 0., 0., 0., 0., 0., 0., 1.],
[0., 1., 0., 0., 1., 0., 0., 0.],
[0., 1., 0., 0., 0., 1., 0., 0.],
[0., 1., 0., 0., 0., 0., 1., 0.],
[0., 0., 1., 0., 1., 0., 0., 0.],
[0., 0., 1., 0., 0., 1., 0., 0.],
[0., 0., 0., 1., 1., 0., 0., 0.]])
What I'm trying to get is instead an encoding in which all rows for a given type are combined. I.e. an output that looks like
array([[1., 0., 0., 0., 1., 1., 1., 1.],
[0., 1., 0., 0., 1., 1., 1., 0.],
[0., 0., 1., 0., 1., 1., 0., 0.],
[0., 0., 0., 1., 1., 0., 0., 0.]])
where all feats for a given type are switched on, but there is only one row per feat. Is ColumnTransformer the right way to do that? Can I do it with only OneHotEncoder?
I don't care about the identity matrix on the left. Really what I'm after is just
array([[1., 1., 1., 1.],
[1., 1., 1., 0.],
[1., 1., 0., 0.],
[1., 0., 0., 0.]])
I've tried playing around with ColumnTransformer or using just OneHotEncoder with something like
ohe = OneHotEncoder(categories=X['feat'].unique())
for t in X['type'].unique():
print(t)
print(ohe.fit_transform(X[X['type'] == t]).toarray())
with no success.