As quickly sketched in the comment there are a couple of considerations to be done on your example:
method
.fit_transform()generally returns either a sparse matrix or a numpy array. Returning a sparse matrix serves the purpose of saving memory; think to the example where you one-hot-encode a categorical attribute with many categories. You'll end up having a matrix with many columns and a single non-zero entry per row; with a sparse matrix you can store the location of the non-zero element only. In these situation you can call.toarray()on the output of.fit_transform()to get a numpy array back to be passed to thepd.DataFrameconstructor.Actually, on a five-rows dataset similar to the one you provided
df = pd.DataFrame({ 'department': ['operations', 'operations', 'support', 'logistics', 'sales'], 'review': [0.577569, 0.751900, 0.722548, 0.675158, 0.676203], 'projects': [3, 3, 3, 4, 3], 'salary': ['low', 'medium', 'medium', 'low', 'high'], 'satisfaction': [0.626759, 0.751900, 0.722548, 0.675158, 0.676203], 'bonus': [0, 0, 0, 0, 1], 'avg_hrs_month': [180.866070, 182.708149, 184.416084, 188.707545, 179.821083], 'left': [0, 0, 1, 0, 0] }) ord_features = ["salary"] ordinal_transformer = OrdinalEncoder() cat_features = ["department"] categorical_transformer = OneHotEncoder(handle_unknown="ignore") ct = ColumnTransformer(transformers=[ ("ord", ordinal_transformer, ord_features), ("cat", categorical_transformer, cat_features), ])I can't reproduce your issue (namely, I directly obtain a numpy array), but basically
pd.DataFrame(ct.fit_transform(df).toarray())should work for your case. This is the output you would get:
As you can see, with respect to your expected output, this only contains the transformed (ordinally encoded) salary column as first column and the transformed (one-hot-encoded) department column from the second to the last column. That's because, as you can see within the docs, parameter
remainderis set to'drop'by default, which implies that all columns which are not subject to transformation are dropped. To avoid this, you should set it to'passthrough'; this will help you to transform the columns you need and keep the other untouched.ct = ColumnTransformer(transformers=[ ("ord", ordinal_transformer, ord_features), ("cat", categorical_transformer, cat_features )], remainder='passthrough' )This would be the output of your
pd.DataFrame(ct.fit_transform(df).toarray())in such a case:
Again, as you can see also column order is not the one you would expect after the transformation. Long story short, that's because in a
ColumnTransformer
The order of the columns in the transformed feature matrix follows the order of how the columns are specified in the transformers list. Columns of the original feature matrix that are not specified are dropped from the resulting transformed feature matrix, unless specified in the passthrough keyword. Those columns specified with passthrough are added at the right to the output of the transformers.
I would aggest reading Preserve column order after applying sklearn.compose.ColumnTransformer at this proposal.
- Eventually, for what concerns column names you should probably apply a custom solution passing what you want directly to the
columnsparameter to be passed to thepd.DataFrameconstructor. Indeed,OrdinalEncoder(differently fromOneHotEncoder) does not provide a.get_feature_names_out()method that makes it generally easy to passcolumns=ct.get_feature_names_out()to thepd.DataFrameconstructor. See ColumnTransformer & Pipeline with OHE - Is the OHE encoded field retained or removed after ct is performed? for an example of its usage.
Update 10/2022 - sklearn version 1.2.dev0
With sklearn version 1.2.0 it will be possible to solve the problem of returning a DataFrame when transforming a ColumnTransformer instance much more easily. Such version has not been released yet, but you can test the following in dev (version 1.2.dev0), by installing the nightly builds as such:
pip install --pre --extra-index https://pypi.anaconda.org/scipy-wheels-nightly/simple scikit-learn -U
The ColumnTransformer (and other transformers as well) now exposes a .set_output() method which gives the possibility to configure a transformer to output pandas DataFrames, by passing parameter transform='pandas' to it.
Therefore, the example becomes:
import pandas as pd
from sklearn.preprocessing import LabelEncoder, OneHotEncoder, OrdinalEncoder
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.ensemble import RandomForestClassifier
df = pd.DataFrame({
'department': ['operations', 'operations', 'support', 'logistics', 'sales'],
'review': [0.577569, 0.751900, 0.722548, 0.675158, 0.676203],
'projects': [3, 3, 3, 4, 3],
'salary': ['low', 'medium', 'medium', 'low', 'high'],
'satisfaction': [0.626759, 0.751900, 0.722548, 0.675158, 0.676203],
'bonus': [0, 0, 0, 0, 1],
'avg_hrs_month': [180.866070, 182.708149, 184.416084, 188.707545, 179.821083],
'left': [0, 0, 1, 0, 0]
})
ord_features = ["salary"]
ordinal_transformer = OrdinalEncoder()
cat_features = ["department"]
categorical_transformer = OneHotEncoder(sparse_output=False, handle_unknown="ignore")
ct = ColumnTransformer(transformers=[
("ord", ordinal_transformer, ord_features),
("cat", categorical_transformer, cat_features )],
remainder='passthrough'
)
ct.set_output('pandas')
df_pandas = ct.fit_transform(df)
df_pandas

The output also becomes much easier to read as it has proper column names (indeed, at each step, the transformers of which ColumnTransformer is made of do have the attribute feature_names_in_; so you don't lose column names anymore while transforming the input).
Last note. Observe that the example now requires parameter sparse_output=False to be passed to the OneHotEncoder instance in order to work.
This answer skips the workaround and directly provides a solution for scikit-learn version 1.2+
From sklearn version 1.2 on, transformers can return a pandas DataFrame directly without further handling. It is done with set_output, which can be configured per estimator by calling the set_output method or globally by setting set_config(transform_output="pandas"). See Release Highlights for scikit-learn 1.2 - Pandas output with set_output API
In your case the solution would be:
ord_features = ["salary"]
ordinal_transformer = OrdinalEncoder()
cat_features = ["department"]
categorical_transformer = OneHotEncoder(handle_unknown="ignore")
ct = ColumnTransformer(
transformers=[
("ord", ordinal_transformer, ord_features),
("cat", categorical_transformer, cat_features ),
]
)
# Add the following line to your code
ct.set_output(transform="pandas")
df_new = ct.fit_transform(df)
df_new
I've tried this with an sklearn builtin dataset rather than yours, but the only difference appears to be the order of the columns. Switching the order of the elements in the transformer lists produces the same results. (In both cases, the numeric columns and categorical one-hot encoded columns are separated from each other, but are placed in the order that they appear in the transformer list.)
Both of these methods are used to combine independent transformations (transformers) into a single transformer, by independent I mean transformation (transformers) that don't need to be executed in a defined order. That's because unlike in regular pipelines, one transformer is not applied to the output of another transformer.
The main difference is that: each transformer in a feature union object gets the whole data as input. While in column transformer object they get only part of the data as input. Both of them concatenate the results of each transformer in the end. Both can use parallel processing.