1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604
|
"""
The :mod:`sklearn.compose._column_transformer` module implements utilities
to work with heterogeneous data and to apply different transformers to
different columns.
"""
# Authors: The scikit-learn developers
# SPDX-License-Identifier: BSD-3-Clause
import warnings
from collections import Counter
from functools import partial
from itertools import chain
from numbers import Integral, Real
import numpy as np
from scipy import sparse
from ..base import TransformerMixin, _fit_context, clone
from ..pipeline import _fit_transform_one, _name_estimators, _transform_one
from ..preprocessing import FunctionTransformer
from ..utils import Bunch
from ..utils._indexing import _determine_key_type, _get_column_indices, _safe_indexing
from ..utils._metadata_requests import METHODS
from ..utils._param_validation import HasMethods, Hidden, Interval, StrOptions
from ..utils._repr_html.estimator import _VisualBlock
from ..utils._set_output import (
_get_container_adapter,
_get_output_config,
_safe_set_output,
)
from ..utils._tags import get_tags
from ..utils.metadata_routing import (
MetadataRouter,
MethodMapping,
_raise_for_params,
_routing_enabled,
process_routing,
)
from ..utils.metaestimators import _BaseComposition
from ..utils.parallel import Parallel, delayed
from ..utils.validation import (
_check_feature_names,
_check_feature_names_in,
_check_n_features,
_get_feature_names,
_is_pandas_df,
_num_samples,
check_array,
check_is_fitted,
)
__all__ = ["ColumnTransformer", "make_column_selector", "make_column_transformer"]
_ERR_MSG_1DCOLUMN = (
"1D data passed to a transformer that expects 2D data. "
"Try to specify the column selection as a list of one "
"item instead of a scalar."
)
class ColumnTransformer(TransformerMixin, _BaseComposition):
"""Applies transformers to columns of an array or pandas DataFrame.
This estimator allows different columns or column subsets of the input
to be transformed separately and the features generated by each transformer
will be concatenated to form a single feature space.
This is useful for heterogeneous or columnar data, to combine several
feature extraction mechanisms or transformations into a single transformer.
Read more in the :ref:`User Guide <column_transformer>`.
.. versionadded:: 0.20
Parameters
----------
transformers : list of tuples
List of (name, transformer, columns) tuples specifying the
transformer objects to be applied to subsets of the data.
name : str
Like in Pipeline and FeatureUnion, this allows the transformer and
its parameters to be set using ``set_params`` and searched in grid
search.
transformer : {'drop', 'passthrough'} or estimator
Estimator must support :term:`fit` and :term:`transform`.
Special-cased strings 'drop' and 'passthrough' are accepted as
well, to indicate to drop the columns or to pass them through
untransformed, respectively.
columns : str, array-like of str, int, array-like of int, \
array-like of bool, slice or callable
Indexes the data on its second axis. Integers are interpreted as
positional columns, while strings can reference DataFrame columns
by name. A scalar string or int should be used where
``transformer`` expects X to be a 1d array-like (vector),
otherwise a 2d array will be passed to the transformer.
A callable is passed the input data `X` and can return any of the
above. To select multiple columns by name or dtype, you can use
:obj:`make_column_selector`.
remainder : {'drop', 'passthrough'} or estimator, default='drop'
By default, only the specified columns in `transformers` are
transformed and combined in the output, and the non-specified
columns are dropped. (default of ``'drop'``).
By specifying ``remainder='passthrough'``, all remaining columns that
were not specified in `transformers`, but present in the data passed
to `fit` will be automatically passed through. This subset of columns
is concatenated with the output of the transformers. For dataframes,
extra columns not seen during `fit` will be excluded from the output
of `transform`.
By setting ``remainder`` to be an estimator, the remaining
non-specified columns will use the ``remainder`` estimator. The
estimator must support :term:`fit` and :term:`transform`.
Note that using this feature requires that the DataFrame columns
input at :term:`fit` and :term:`transform` have identical order.
sparse_threshold : float, default=0.3
If the output of the different transformers contains sparse matrices,
these will be stacked as a sparse matrix if the overall density is
lower than this value. Use ``sparse_threshold=0`` to always return
dense. When the transformed output consists of all dense data, the
stacked result will be dense, and this keyword will be ignored.
n_jobs : int, default=None
Number of jobs to run in parallel.
``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
``-1`` means using all processors. See :term:`Glossary <n_jobs>`
for more details.
transformer_weights : dict, default=None
Multiplicative weights for features per transformer. The output of the
transformer is multiplied by these weights. Keys are transformer names,
values the weights.
verbose : bool, default=False
If True, the time elapsed while fitting each transformer will be
printed as it is completed.
verbose_feature_names_out : bool, str or Callable[[str, str], str], default=True
- If True, :meth:`ColumnTransformer.get_feature_names_out` will prefix
all feature names with the name of the transformer that generated that
feature. It is equivalent to setting
`verbose_feature_names_out="{transformer_name}__{feature_name}"`.
- If False, :meth:`ColumnTransformer.get_feature_names_out` will not
prefix any feature names and will error if feature names are not
unique.
- If ``Callable[[str, str], str]``,
:meth:`ColumnTransformer.get_feature_names_out` will rename all the features
using the name of the transformer. The first argument of the callable is the
transformer name and the second argument is the feature name. The returned
string will be the new feature name.
- If ``str``, it must be a string ready for formatting. The given string will
be formatted using two field names: ``transformer_name`` and ``feature_name``.
e.g. ``"{feature_name}__{transformer_name}"``. See :meth:`str.format` method
from the standard library for more info.
.. versionadded:: 1.0
.. versionchanged:: 1.6
`verbose_feature_names_out` can be a callable or a string to be formatted.
force_int_remainder_cols : bool, default=False
This parameter has no effect.
.. note::
If you do not access the list of columns for the remainder columns
in the `transformers_` fitted attribute, you do not need to set
this parameter.
.. versionadded:: 1.5
.. versionchanged:: 1.7
The default value for `force_int_remainder_cols` will change from
`True` to `False` in version 1.7.
.. deprecated:: 1.7
`force_int_remainder_cols` is deprecated and will be removed in 1.9.
Attributes
----------
transformers_ : list
The collection of fitted transformers as tuples of (name,
fitted_transformer, column). `fitted_transformer` can be an estimator,
or `'drop'`; `'passthrough'` is replaced with an equivalent
:class:`~sklearn.preprocessing.FunctionTransformer`. In case there were
no columns selected, this will be the unfitted transformer. If there
are remaining columns, the final element is a tuple of the form:
('remainder', transformer, remaining_columns) corresponding to the
``remainder`` parameter. If there are remaining columns, then
``len(transformers_)==len(transformers)+1``, otherwise
``len(transformers_)==len(transformers)``.
.. versionadded:: 1.7
The format of the remaining columns now attempts to match that of the other
transformers: if all columns were provided as column names (`str`), the
remaining columns are stored as column names; if all columns were provided
as mask arrays (`bool`), so are the remaining columns; in all other cases
the remaining columns are stored as indices (`int`).
named_transformers_ : :class:`~sklearn.utils.Bunch`
Read-only attribute to access any transformer by given name.
Keys are transformer names and values are the fitted transformer
objects.
sparse_output_ : bool
Boolean flag indicating whether the output of ``transform`` is a
sparse matrix or a dense numpy array, which depends on the output
of the individual transformers and the `sparse_threshold` keyword.
output_indices_ : dict
A dictionary from each transformer name to a slice, where the slice
corresponds to indices in the transformed output. This is useful to
inspect which transformer is responsible for which transformed
feature(s).
.. versionadded:: 1.0
n_features_in_ : int
Number of features seen during :term:`fit`. Only defined if the
underlying transformers expose such an attribute when fit.
.. versionadded:: 0.24
feature_names_in_ : ndarray of shape (`n_features_in_`,)
Names of features seen during :term:`fit`. Defined only when `X`
has feature names that are all strings.
.. versionadded:: 1.0
See Also
--------
make_column_transformer : Convenience function for
combining the outputs of multiple transformer objects applied to
column subsets of the original feature space.
make_column_selector : Convenience function for selecting
columns based on datatype or the columns name with a regex pattern.
Notes
-----
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.
Examples
--------
>>> import numpy as np
>>> from sklearn.compose import ColumnTransformer
>>> from sklearn.preprocessing import Normalizer
>>> ct = ColumnTransformer(
... [("norm1", Normalizer(norm='l1'), [0, 1]),
... ("norm2", Normalizer(norm='l1'), slice(2, 4))])
>>> X = np.array([[0., 1., 2., 2.],
... [1., 1., 0., 1.]])
>>> # Normalizer scales each row of X to unit norm. A separate scaling
>>> # is applied for the two first and two last elements of each
>>> # row independently.
>>> ct.fit_transform(X)
array([[0. , 1. , 0.5, 0.5],
[0.5, 0.5, 0. , 1. ]])
:class:`ColumnTransformer` can be configured with a transformer that requires
a 1d array by setting the column to a string:
>>> from sklearn.feature_extraction.text import CountVectorizer
>>> from sklearn.preprocessing import MinMaxScaler
>>> import pandas as pd # doctest: +SKIP
>>> X = pd.DataFrame({
... "documents": ["First item", "second one here", "Is this the last?"],
... "width": [3, 4, 5],
... }) # doctest: +SKIP
>>> # "documents" is a string which configures ColumnTransformer to
>>> # pass the documents column as a 1d array to the CountVectorizer
>>> ct = ColumnTransformer(
... [("text_preprocess", CountVectorizer(), "documents"),
... ("num_preprocess", MinMaxScaler(), ["width"])])
>>> X_trans = ct.fit_transform(X) # doctest: +SKIP
For a more detailed example of usage, see
:ref:`sphx_glr_auto_examples_compose_plot_column_transformer_mixed_types.py`.
"""
_parameter_constraints: dict = {
"transformers": [list, Hidden(tuple)],
"remainder": [
StrOptions({"drop", "passthrough"}),
HasMethods(["fit", "transform"]),
HasMethods(["fit_transform", "transform"]),
],
"sparse_threshold": [Interval(Real, 0, 1, closed="both")],
"n_jobs": [Integral, None],
"transformer_weights": [dict, None],
"verbose": ["verbose"],
"verbose_feature_names_out": ["boolean", str, callable],
"force_int_remainder_cols": ["boolean", Hidden(StrOptions({"deprecated"}))],
}
def __init__(
self,
transformers,
*,
remainder="drop",
sparse_threshold=0.3,
n_jobs=None,
transformer_weights=None,
verbose=False,
verbose_feature_names_out=True,
force_int_remainder_cols="deprecated",
):
self.transformers = transformers
self.remainder = remainder
self.sparse_threshold = sparse_threshold
self.n_jobs = n_jobs
self.transformer_weights = transformer_weights
self.verbose = verbose
self.verbose_feature_names_out = verbose_feature_names_out
self.force_int_remainder_cols = force_int_remainder_cols
@property
def _transformers(self):
"""
Internal list of transformer only containing the name and
transformers, dropping the columns.
DO NOT USE: This is for the implementation of get_params via
BaseComposition._get_params which expects lists of tuples of len 2.
To iterate through the transformers, use ``self._iter`` instead.
"""
try:
return [(name, trans) for name, trans, _ in self.transformers]
except (TypeError, ValueError):
return self.transformers
@_transformers.setter
def _transformers(self, value):
"""DO NOT USE: This is for the implementation of set_params via
BaseComposition._get_params which gives lists of tuples of len 2.
"""
try:
self.transformers = [
(name, trans, col)
for ((name, trans), (_, _, col)) in zip(value, self.transformers)
]
except (TypeError, ValueError):
self.transformers = value
def set_output(self, *, transform=None):
"""Set the output container when `"transform"` and `"fit_transform"` are called.
Calling `set_output` will set the output of all estimators in `transformers`
and `transformers_`.
Parameters
----------
transform : {"default", "pandas", "polars"}, default=None
Configure output of `transform` and `fit_transform`.
- `"default"`: Default output format of a transformer
- `"pandas"`: DataFrame output
- `"polars"`: Polars output
- `None`: Transform configuration is unchanged
.. versionadded:: 1.4
`"polars"` option was added.
Returns
-------
self : estimator instance
Estimator instance.
"""
super().set_output(transform=transform)
transformers = (
trans
for _, trans, _ in chain(
self.transformers, getattr(self, "transformers_", [])
)
if trans not in {"passthrough", "drop"}
)
for trans in transformers:
_safe_set_output(trans, transform=transform)
if self.remainder not in {"passthrough", "drop"}:
_safe_set_output(self.remainder, transform=transform)
return self
def get_params(self, deep=True):
"""Get parameters for this estimator.
Returns the parameters given in the constructor as well as the
estimators contained within the `transformers` of the
`ColumnTransformer`.
Parameters
----------
deep : bool, default=True
If True, will return the parameters for this estimator and
contained subobjects that are estimators.
Returns
-------
params : dict
Parameter names mapped to their values.
"""
return self._get_params("_transformers", deep=deep)
def set_params(self, **kwargs):
"""Set the parameters of this estimator.
Valid parameter keys can be listed with ``get_params()``. Note that you
can directly set the parameters of the estimators contained in
`transformers` of `ColumnTransformer`.
Parameters
----------
**kwargs : dict
Estimator parameters.
Returns
-------
self : ColumnTransformer
This estimator.
"""
self._set_params("_transformers", **kwargs)
return self
def _iter(self, fitted, column_as_labels, skip_drop, skip_empty_columns):
"""
Generate (name, trans, columns, weight) tuples.
Parameters
----------
fitted : bool
If True, use the fitted transformers (``self.transformers_``) to
iterate through transformers, else use the transformers passed by
the user (``self.transformers``).
column_as_labels : bool
If True, columns are returned as string labels. If False, columns
are returned as they were given by the user. This can only be True
if the ``ColumnTransformer`` is already fitted.
skip_drop : bool
If True, 'drop' transformers are filtered out.
skip_empty_columns : bool
If True, transformers with empty selected columns are filtered out.
Yields
------
A generator of tuples containing:
- name : the name of the transformer
- transformer : the transformer object
- columns : the columns for that transformer
- weight : the weight of the transformer
"""
if fitted:
transformers = self.transformers_
else:
# interleave the validated column specifiers
transformers = [
(name, trans, column)
for (name, trans, _), column in zip(self.transformers, self._columns)
]
# add transformer tuple for remainder
if self._remainder[2]:
transformers = chain(transformers, [self._remainder])
get_weight = (self.transformer_weights or {}).get
for name, trans, columns in transformers:
if skip_drop and trans == "drop":
continue
if skip_empty_columns and _is_empty_column_selection(columns):
continue
if column_as_labels:
# Convert all columns to using their string labels
columns_is_scalar = np.isscalar(columns)
indices = self._transformer_to_input_indices[name]
columns = self.feature_names_in_[indices]
if columns_is_scalar:
# selection is done with one dimension
columns = columns[0]
yield (name, trans, columns, get_weight(name))
def _validate_transformers(self):
"""Validate names of transformers and the transformers themselves.
This checks whether given transformers have the required methods, i.e.
`fit` or `fit_transform` and `transform` implemented.
"""
if not self.transformers:
return
names, transformers, _ = zip(*self.transformers)
# validate names
self._validate_names(names)
# validate estimators
for t in transformers:
if t in ("drop", "passthrough"):
continue
if not (hasattr(t, "fit") or hasattr(t, "fit_transform")) or not hasattr(
t, "transform"
):
# Used to validate the transformers in the `transformers` list
raise TypeError(
"All estimators should implement fit and "
"transform, or can be 'drop' or 'passthrough' "
"specifiers. '%s' (type %s) doesn't." % (t, type(t))
)
def _validate_column_callables(self, X):
"""
Converts callable column specifications.
This stores a dictionary of the form `{step_name: column_indices}` and
calls the `columns` on `X` if `columns` is a callable for a given
transformer.
The results are then stored in `self._transformer_to_input_indices`.
"""
all_columns = []
transformer_to_input_indices = {}
for name, _, columns in self.transformers:
if callable(columns):
columns = columns(X)
all_columns.append(columns)
transformer_to_input_indices[name] = _get_column_indices(X, columns)
self._columns = all_columns
self._transformer_to_input_indices = transformer_to_input_indices
def _validate_remainder(self, X):
"""
Validates ``remainder`` and defines ``_remainder`` targeting
the remaining columns.
"""
cols = set(chain(*self._transformer_to_input_indices.values()))
remaining = sorted(set(range(self.n_features_in_)) - cols)
self._transformer_to_input_indices["remainder"] = remaining
remainder_cols = self._get_remainder_cols(remaining)
self._remainder = ("remainder", self.remainder, remainder_cols)
def _get_remainder_cols_dtype(self):
try:
all_dtypes = {_determine_key_type(c) for (*_, c) in self.transformers}
if len(all_dtypes) == 1:
return next(iter(all_dtypes))
except ValueError:
# _determine_key_type raises a ValueError if some transformer
# columns are Callables
return "int"
return "int"
def _get_remainder_cols(self, indices):
dtype = self._get_remainder_cols_dtype()
if dtype == "str":
return list(self.feature_names_in_[indices])
if dtype == "bool":
return [i in indices for i in range(self.n_features_in_)]
return indices
@property
def named_transformers_(self):
"""Access the fitted transformer by name.
Read-only attribute to access any transformer by given name.
Keys are transformer names and values are the fitted transformer
objects.
"""
# Use Bunch object to improve autocomplete
return Bunch(**{name: trans for name, trans, _ in self.transformers_})
def _get_feature_name_out_for_transformer(self, name, trans, feature_names_in):
"""Gets feature names of transformer.
Used in conjunction with self._iter(fitted=True) in get_feature_names_out.
"""
column_indices = self._transformer_to_input_indices[name]
names = feature_names_in[column_indices]
# An actual transformer
if not hasattr(trans, "get_feature_names_out"):
raise AttributeError(
f"Transformer {name} (type {type(trans).__name__}) does "
"not provide get_feature_names_out."
)
return trans.get_feature_names_out(names)
def get_feature_names_out(self, input_features=None):
"""Get output feature names for transformation.
Parameters
----------
input_features : array-like of str or None, default=None
Input features.
- If `input_features` is `None`, then `feature_names_in_` is
used as feature names in. If `feature_names_in_` is not defined,
then the following input feature names are generated:
`["x0", "x1", ..., "x(n_features_in_ - 1)"]`.
- If `input_features` is an array-like, then `input_features` must
match `feature_names_in_` if `feature_names_in_` is defined.
Returns
-------
feature_names_out : ndarray of str objects
Transformed feature names.
"""
check_is_fitted(self)
input_features = _check_feature_names_in(self, input_features)
# List of tuples (name, feature_names_out)
transformer_with_feature_names_out = []
for name, trans, *_ in self._iter(
fitted=True,
column_as_labels=False,
skip_empty_columns=True,
skip_drop=True,
):
feature_names_out = self._get_feature_name_out_for_transformer(
name, trans, input_features
)
if feature_names_out is None:
continue
transformer_with_feature_names_out.append((name, feature_names_out))
if not transformer_with_feature_names_out:
# No feature names
return np.array([], dtype=object)
return self._add_prefix_for_feature_names_out(
transformer_with_feature_names_out
)
def _add_prefix_for_feature_names_out(self, transformer_with_feature_names_out):
"""Add prefix for feature names out that includes the transformer names.
Parameters
----------
transformer_with_feature_names_out : list of tuples of (str, array-like of str)
The tuple consistent of the transformer's name and its feature names out.
Returns
-------
feature_names_out : ndarray of shape (n_features,), dtype=str
Transformed feature names.
"""
feature_names_out_callable = None
if callable(self.verbose_feature_names_out):
feature_names_out_callable = self.verbose_feature_names_out
elif isinstance(self.verbose_feature_names_out, str):
feature_names_out_callable = partial(
_feature_names_out_with_str_format,
str_format=self.verbose_feature_names_out,
)
elif self.verbose_feature_names_out is True:
feature_names_out_callable = partial(
_feature_names_out_with_str_format,
str_format="{transformer_name}__{feature_name}",
)
if feature_names_out_callable is not None:
# Prefix the feature names out with the transformers name
names = list(
chain.from_iterable(
(feature_names_out_callable(name, i) for i in feature_names_out)
for name, feature_names_out in transformer_with_feature_names_out
)
)
return np.asarray(names, dtype=object)
# verbose_feature_names_out is False
# Check that names are all unique without a prefix
feature_names_count = Counter(
chain.from_iterable(s for _, s in transformer_with_feature_names_out)
)
top_6_overlap = [
name for name, count in feature_names_count.most_common(6) if count > 1
]
top_6_overlap.sort()
if top_6_overlap:
if len(top_6_overlap) == 6:
# There are more than 5 overlapping names, we only show the 5
# of the feature names
names_repr = str(top_6_overlap[:5])[:-1] + ", ...]"
else:
names_repr = str(top_6_overlap)
raise ValueError(
f"Output feature names: {names_repr} are not unique. Please set "
"verbose_feature_names_out=True to add prefixes to feature names"
)
return np.concatenate(
[name for _, name in transformer_with_feature_names_out],
)
def _update_fitted_transformers(self, transformers):
"""Set self.transformers_ from given transformers.
Parameters
----------
transformers : list of estimators
The fitted estimators as the output of
`self._call_func_on_transformers(func=_fit_transform_one, ...)`.
That function doesn't include 'drop' or transformers for which no
column is selected. 'drop' is kept as is, and for the no-column
transformers the unfitted transformer is put in
`self.transformers_`.
"""
# transformers are fitted; excludes 'drop' cases
fitted_transformers = iter(transformers)
transformers_ = []
for name, old, column, _ in self._iter(
fitted=False,
column_as_labels=False,
skip_drop=False,
skip_empty_columns=False,
):
if old == "drop":
trans = "drop"
elif _is_empty_column_selection(column):
trans = old
else:
trans = next(fitted_transformers)
transformers_.append((name, trans, column))
# sanity check that transformers is exhausted
assert not list(fitted_transformers)
self.transformers_ = transformers_
def _validate_output(self, result):
"""
Ensure that the output of each transformer is 2D. Otherwise
hstack can raise an error or produce incorrect results.
"""
names = [
name
for name, _, _, _ in self._iter(
fitted=True,
column_as_labels=False,
skip_drop=True,
skip_empty_columns=True,
)
]
for Xs, name in zip(result, names):
if not getattr(Xs, "ndim", 0) == 2 and not hasattr(Xs, "__dataframe__"):
raise ValueError(
"The output of the '{0}' transformer should be 2D (numpy array, "
"scipy sparse array, dataframe).".format(name)
)
if _get_output_config("transform", self)["dense"] == "pandas":
return
try:
import pandas as pd
except ImportError:
return
for Xs, name in zip(result, names):
if not _is_pandas_df(Xs):
continue
for col_name, dtype in Xs.dtypes.to_dict().items():
if getattr(dtype, "na_value", None) is not pd.NA:
continue
if pd.NA not in Xs[col_name].values:
continue
class_name = self.__class__.__name__
raise ValueError(
f"The output of the '{name}' transformer for column"
f" '{col_name}' has dtype {dtype} and uses pandas.NA to"
" represent null values. Storing this output in a numpy array"
" can cause errors in downstream scikit-learn estimators, and"
" inefficiencies. To avoid this problem you can (i)"
" store the output in a pandas DataFrame by using"
f" {class_name}.set_output(transform='pandas') or (ii) modify"
f" the input data or the '{name}' transformer to avoid the"
" presence of pandas.NA (for example by using"
" pandas.DataFrame.astype)."
)
def _record_output_indices(self, Xs):
"""
Record which transformer produced which column.
"""
idx = 0
self.output_indices_ = {}
for transformer_idx, (name, _, _, _) in enumerate(
self._iter(
fitted=True,
column_as_labels=False,
skip_drop=True,
skip_empty_columns=True,
)
):
n_columns = Xs[transformer_idx].shape[1]
self.output_indices_[name] = slice(idx, idx + n_columns)
idx += n_columns
# `_iter` only generates transformers that have a non empty
# selection. Here we set empty slices for transformers that
# generate no output, which are safe for indexing
all_names = [t[0] for t in self.transformers] + ["remainder"]
for name in all_names:
if name not in self.output_indices_:
self.output_indices_[name] = slice(0, 0)
def _log_message(self, name, idx, total):
if not self.verbose:
return None
return "(%d of %d) Processing %s" % (idx, total, name)
def _call_func_on_transformers(self, X, y, func, column_as_labels, routed_params):
"""
Private function to fit and/or transform on demand.
Parameters
----------
X : {array-like, dataframe} of shape (n_samples, n_features)
The data to be used in fit and/or transform.
y : array-like of shape (n_samples,)
Targets.
func : callable
Function to call, which can be _fit_transform_one or
_transform_one.
column_as_labels : bool
Used to iterate through transformers. If True, columns are returned
as strings. If False, columns are returned as they were given by
the user. Can be True only if the ``ColumnTransformer`` is already
fitted.
routed_params : dict
The routed parameters as the output from ``process_routing``.
Returns
-------
Return value (transformers and/or transformed X data) depends
on the passed function.
"""
if func is _fit_transform_one:
fitted = False
else: # func is _transform_one
fitted = True
transformers = list(
self._iter(
fitted=fitted,
column_as_labels=column_as_labels,
skip_drop=True,
skip_empty_columns=True,
)
)
try:
jobs = []
for idx, (name, trans, columns, weight) in enumerate(transformers, start=1):
if func is _fit_transform_one:
if trans == "passthrough":
output_config = _get_output_config("transform", self)
trans = FunctionTransformer(
accept_sparse=True,
check_inverse=False,
feature_names_out="one-to-one",
).set_output(transform=output_config["dense"])
extra_args = dict(
message_clsname="ColumnTransformer",
message=self._log_message(name, idx, len(transformers)),
)
else: # func is _transform_one
extra_args = {}
jobs.append(
delayed(func)(
transformer=clone(trans) if not fitted else trans,
X=_safe_indexing(X, columns, axis=1),
y=y,
weight=weight,
**extra_args,
params=routed_params[name],
)
)
return Parallel(n_jobs=self.n_jobs)(jobs)
except ValueError as e:
if "Expected 2D array, got 1D array instead" in str(e):
raise ValueError(_ERR_MSG_1DCOLUMN) from e
else:
raise
def fit(self, X, y=None, **params):
"""Fit all transformers using X.
Parameters
----------
X : {array-like, dataframe} of shape (n_samples, n_features)
Input data, of which specified subsets are used to fit the
transformers.
y : array-like of shape (n_samples,...), default=None
Targets for supervised learning.
**params : dict, default=None
Parameters to be passed to the underlying transformers' ``fit`` and
``transform`` methods.
You can only pass this if metadata routing is enabled, which you
can enable using ``sklearn.set_config(enable_metadata_routing=True)``.
.. versionadded:: 1.4
Returns
-------
self : ColumnTransformer
This estimator.
"""
_raise_for_params(params, self, "fit")
# we use fit_transform to make sure to set sparse_output_ (for which we
# need the transformed data) to have consistent output type in predict
self.fit_transform(X, y=y, **params)
return self
@_fit_context(
# estimators in ColumnTransformer.transformers are not validated yet
prefer_skip_nested_validation=False
)
def fit_transform(self, X, y=None, **params):
"""Fit all transformers, transform the data and concatenate results.
Parameters
----------
X : {array-like, dataframe} of shape (n_samples, n_features)
Input data, of which specified subsets are used to fit the
transformers.
y : array-like of shape (n_samples,), default=None
Targets for supervised learning.
**params : dict, default=None
Parameters to be passed to the underlying transformers' ``fit`` and
``transform`` methods.
You can only pass this if metadata routing is enabled, which you
can enable using ``sklearn.set_config(enable_metadata_routing=True)``.
.. versionadded:: 1.4
Returns
-------
X_t : {array-like, sparse matrix} of \
shape (n_samples, sum_n_components)
Horizontally stacked results of transformers. sum_n_components is the
sum of n_components (output dimension) over transformers. If
any result is a sparse matrix, everything will be converted to
sparse matrices.
"""
_raise_for_params(params, self, "fit_transform")
_check_feature_names(self, X, reset=True)
if self.force_int_remainder_cols != "deprecated":
warnings.warn(
"The parameter `force_int_remainder_cols` is deprecated and will be "
"removed in 1.9. It has no effect. Leave it to its default value to "
"avoid this warning.",
FutureWarning,
)
X = _check_X(X)
# set n_features_in_ attribute
_check_n_features(self, X, reset=True)
self._validate_transformers()
n_samples = _num_samples(X)
self._validate_column_callables(X)
self._validate_remainder(X)
if _routing_enabled():
routed_params = process_routing(self, "fit_transform", **params)
else:
routed_params = self._get_empty_routing()
result = self._call_func_on_transformers(
X,
y,
_fit_transform_one,
column_as_labels=False,
routed_params=routed_params,
)
if not result:
self._update_fitted_transformers([])
# All transformers are None
return np.zeros((n_samples, 0))
Xs, transformers = zip(*result)
# determine if concatenated output will be sparse or not
if any(sparse.issparse(X) for X in Xs):
nnz = sum(X.nnz if sparse.issparse(X) else X.size for X in Xs)
total = sum(
X.shape[0] * X.shape[1] if sparse.issparse(X) else X.size for X in Xs
)
density = nnz / total
self.sparse_output_ = density < self.sparse_threshold
else:
self.sparse_output_ = False
self._update_fitted_transformers(transformers)
self._validate_output(Xs)
self._record_output_indices(Xs)
return self._hstack(list(Xs), n_samples=n_samples)
def transform(self, X, **params):
"""Transform X separately by each transformer, concatenate results.
Parameters
----------
X : {array-like, dataframe} of shape (n_samples, n_features)
The data to be transformed by subset.
**params : dict, default=None
Parameters to be passed to the underlying transformers' ``transform``
method.
You can only pass this if metadata routing is enabled, which you
can enable using ``sklearn.set_config(enable_metadata_routing=True)``.
.. versionadded:: 1.4
Returns
-------
X_t : {array-like, sparse matrix} of \
shape (n_samples, sum_n_components)
Horizontally stacked results of transformers. sum_n_components is the
sum of n_components (output dimension) over transformers. If
any result is a sparse matrix, everything will be converted to
sparse matrices.
"""
_raise_for_params(params, self, "transform")
check_is_fitted(self)
X = _check_X(X)
# If ColumnTransformer is fit using a dataframe, and now a dataframe is
# passed to be transformed, we select columns by name instead. This
# enables the user to pass X at transform time with extra columns which
# were not present in fit time, and the order of the columns doesn't
# matter.
fit_dataframe_and_transform_dataframe = hasattr(self, "feature_names_in_") and (
_is_pandas_df(X) or hasattr(X, "__dataframe__")
)
n_samples = _num_samples(X)
column_names = _get_feature_names(X)
if fit_dataframe_and_transform_dataframe:
named_transformers = self.named_transformers_
# check that all names seen in fit are in transform, unless
# they were dropped
non_dropped_indices = [
ind
for name, ind in self._transformer_to_input_indices.items()
if name in named_transformers and named_transformers[name] != "drop"
]
all_indices = set(chain(*non_dropped_indices))
all_names = set(self.feature_names_in_[ind] for ind in all_indices)
diff = all_names - set(column_names)
if diff:
raise ValueError(f"columns are missing: {diff}")
else:
# ndarray was used for fitting or transforming, thus we only
# check that n_features_in_ is consistent
_check_n_features(self, X, reset=False)
if _routing_enabled():
routed_params = process_routing(self, "transform", **params)
else:
routed_params = self._get_empty_routing()
Xs = self._call_func_on_transformers(
X,
None,
_transform_one,
column_as_labels=fit_dataframe_and_transform_dataframe,
routed_params=routed_params,
)
self._validate_output(Xs)
if not Xs:
# All transformers are None
return np.zeros((n_samples, 0))
return self._hstack(list(Xs), n_samples=n_samples)
def _hstack(self, Xs, *, n_samples):
"""Stacks Xs horizontally.
This allows subclasses to control the stacking behavior, while reusing
everything else from ColumnTransformer.
Parameters
----------
Xs : list of {array-like, sparse matrix, dataframe}
The container to concatenate.
n_samples : int
The number of samples in the input data to checking the transformation
consistency.
"""
if self.sparse_output_:
try:
# since all columns should be numeric before stacking them
# in a sparse matrix, `check_array` is used for the
# dtype conversion if necessary.
converted_Xs = [
check_array(X, accept_sparse=True, ensure_all_finite=False)
for X in Xs
]
except ValueError as e:
raise ValueError(
"For a sparse output, all columns should "
"be a numeric or convertible to a numeric."
) from e
return sparse.hstack(converted_Xs).tocsr()
else:
Xs = [f.toarray() if sparse.issparse(f) else f for f in Xs]
adapter = _get_container_adapter("transform", self)
if adapter and all(adapter.is_supported_container(X) for X in Xs):
# rename before stacking as it avoids to error on temporary duplicated
# columns
transformer_names = [
t[0]
for t in self._iter(
fitted=True,
column_as_labels=False,
skip_drop=True,
skip_empty_columns=True,
)
]
feature_names_outs = [X.columns for X in Xs if X.shape[1] != 0]
if self.verbose_feature_names_out:
# `_add_prefix_for_feature_names_out` takes care about raising
# an error if there are duplicated columns.
feature_names_outs = self._add_prefix_for_feature_names_out(
list(zip(transformer_names, feature_names_outs))
)
else:
# check for duplicated columns and raise if any
feature_names_outs = list(chain.from_iterable(feature_names_outs))
feature_names_count = Counter(feature_names_outs)
if any(count > 1 for count in feature_names_count.values()):
duplicated_feature_names = sorted(
name
for name, count in feature_names_count.items()
if count > 1
)
err_msg = (
"Duplicated feature names found before concatenating the"
" outputs of the transformers:"
f" {duplicated_feature_names}.\n"
)
for transformer_name, X in zip(transformer_names, Xs):
if X.shape[1] == 0:
continue
dup_cols_in_transformer = sorted(
set(X.columns).intersection(duplicated_feature_names)
)
if len(dup_cols_in_transformer):
err_msg += (
f"Transformer {transformer_name} has conflicting "
f"columns names: {dup_cols_in_transformer}.\n"
)
raise ValueError(
err_msg
+ "Either make sure that the transformers named above "
"do not generate columns with conflicting names or set "
"verbose_feature_names_out=True to automatically "
"prefix to the output feature names with the name "
"of the transformer to prevent any conflicting "
"names."
)
names_idx = 0
for X in Xs:
if X.shape[1] == 0:
continue
names_out = feature_names_outs[names_idx : names_idx + X.shape[1]]
adapter.rename_columns(X, names_out)
names_idx += X.shape[1]
output = adapter.hstack(Xs)
output_samples = output.shape[0]
if output_samples != n_samples:
raise ValueError(
"Concatenating DataFrames from the transformer's output lead to"
" an inconsistent number of samples. The output may have Pandas"
" Indexes that do not match, or that transformers are returning"
" number of samples which are not the same as the number input"
" samples."
)
return output
return np.hstack(Xs)
def _sk_visual_block_(self):
if isinstance(self.remainder, str) and self.remainder == "drop":
transformers = self.transformers
elif hasattr(self, "_remainder"):
remainder_columns = self._remainder[2]
if (
hasattr(self, "feature_names_in_")
and remainder_columns
and not all(isinstance(col, str) for col in remainder_columns)
):
remainder_columns = self.feature_names_in_[remainder_columns].tolist()
transformers = chain(
self.transformers, [("remainder", self.remainder, remainder_columns)]
)
else:
transformers = chain(self.transformers, [("remainder", self.remainder, "")])
names, transformers, name_details = zip(*transformers)
return _VisualBlock(
"parallel", transformers, names=names, name_details=name_details
)
def __getitem__(self, key):
try:
return self.named_transformers_[key]
except AttributeError as e:
raise TypeError(
"ColumnTransformer is subscriptable after it is fitted"
) from e
except KeyError as e:
raise KeyError(f"'{key}' is not a valid transformer name") from e
def _get_empty_routing(self):
"""Return empty routing.
Used while routing can be disabled.
TODO: Remove when ``set_config(enable_metadata_routing=False)`` is no
more an option.
"""
return Bunch(
**{
name: Bunch(**{method: {} for method in METHODS})
for name, step, _, _ in self._iter(
fitted=False,
column_as_labels=False,
skip_drop=True,
skip_empty_columns=True,
)
}
)
def get_metadata_routing(self):
"""Get metadata routing of this object.
Please check :ref:`User Guide <metadata_routing>` on how the routing
mechanism works.
.. versionadded:: 1.4
Returns
-------
routing : MetadataRouter
A :class:`~sklearn.utils.metadata_routing.MetadataRouter` encapsulating
routing information.
"""
router = MetadataRouter(owner=self.__class__.__name__)
# Here we don't care about which columns are used for which
# transformers, and whether or not a transformer is used at all, which
# might happen if no columns are selected for that transformer. We
# request all metadata requested by all transformers.
transformers = chain(self.transformers, [("remainder", self.remainder, None)])
for name, step, _ in transformers:
method_mapping = MethodMapping()
if hasattr(step, "fit_transform"):
(
method_mapping.add(caller="fit", callee="fit_transform").add(
caller="fit_transform", callee="fit_transform"
)
)
else:
(
method_mapping.add(caller="fit", callee="fit")
.add(caller="fit", callee="transform")
.add(caller="fit_transform", callee="fit")
.add(caller="fit_transform", callee="transform")
)
method_mapping.add(caller="transform", callee="transform")
router.add(method_mapping=method_mapping, **{name: step})
return router
def __sklearn_tags__(self):
tags = super().__sklearn_tags__()
try:
tags.input_tags.sparse = all(
get_tags(trans).input_tags.sparse
for name, trans, _ in self.transformers
if trans not in {"passthrough", "drop"}
)
except Exception:
# If `transformers` does not comply with our API (list of tuples)
# then it will fail. In this case, we assume that `sparse` is False
# but the parameter validation will raise an error during `fit`.
pass # pragma: no cover
return tags
def _check_X(X):
"""Use check_array only when necessary, e.g. on lists and other non-array-likes."""
if (
(hasattr(X, "__array__") and hasattr(X, "shape"))
or hasattr(X, "__dataframe__")
or sparse.issparse(X)
):
return X
return check_array(X, ensure_all_finite="allow-nan", dtype=object)
def _is_empty_column_selection(column):
"""
Return True if the column selection is empty (empty list or all-False
boolean array).
"""
if (
hasattr(column, "dtype")
# Not necessarily a numpy dtype, can be a pandas dtype as well
and isinstance(column.dtype, np.dtype)
and np.issubdtype(column.dtype, np.bool_)
):
return not column.any()
elif hasattr(column, "__len__"):
return len(column) == 0 or (
all(isinstance(col, bool) for col in column) and not any(column)
)
else:
return False
def _get_transformer_list(estimators):
"""
Construct (name, trans, column) tuples from list
"""
transformers, columns = zip(*estimators)
names, _ = zip(*_name_estimators(transformers))
transformer_list = list(zip(names, transformers, columns))
return transformer_list
# This function is not validated using validate_params because
# it's just a factory for ColumnTransformer.
def make_column_transformer(
*transformers,
remainder="drop",
sparse_threshold=0.3,
n_jobs=None,
verbose=False,
verbose_feature_names_out=True,
force_int_remainder_cols="deprecated",
):
"""Construct a ColumnTransformer from the given transformers.
This is a shorthand for the ColumnTransformer constructor; it does not
require, and does not permit, naming the transformers. Instead, they will
be given names automatically based on their types. It also does not allow
weighting with ``transformer_weights``.
Read more in the :ref:`User Guide <make_column_transformer>`.
Parameters
----------
*transformers : tuples
Tuples of the form (transformer, columns) specifying the
transformer objects to be applied to subsets of the data.
transformer : {'drop', 'passthrough'} or estimator
Estimator must support :term:`fit` and :term:`transform`.
Special-cased strings 'drop' and 'passthrough' are accepted as
well, to indicate to drop the columns or to pass them through
untransformed, respectively.
columns : str, array-like of str, int, array-like of int, slice, \
array-like of bool or callable
Indexes the data on its second axis. Integers are interpreted as
positional columns, while strings can reference DataFrame columns
by name. A scalar string or int should be used where
``transformer`` expects X to be a 1d array-like (vector),
otherwise a 2d array will be passed to the transformer.
A callable is passed the input data `X` and can return any of the
above. To select multiple columns by name or dtype, you can use
:obj:`make_column_selector`.
remainder : {'drop', 'passthrough'} or estimator, default='drop'
By default, only the specified columns in `transformers` are
transformed and combined in the output, and the non-specified
columns are dropped. (default of ``'drop'``).
By specifying ``remainder='passthrough'``, all remaining columns that
were not specified in `transformers` will be automatically passed
through. This subset of columns is concatenated with the output of
the transformers.
By setting ``remainder`` to be an estimator, the remaining
non-specified columns will use the ``remainder`` estimator. The
estimator must support :term:`fit` and :term:`transform`.
sparse_threshold : float, default=0.3
If the transformed output consists of a mix of sparse and dense data,
it will be stacked as a sparse matrix if the density is lower than this
value. Use ``sparse_threshold=0`` to always return dense.
When the transformed output consists of all sparse or all dense data,
the stacked result will be sparse or dense, respectively, and this
keyword will be ignored.
n_jobs : int, default=None
Number of jobs to run in parallel.
``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
``-1`` means using all processors. See :term:`Glossary <n_jobs>`
for more details.
verbose : bool, default=False
If True, the time elapsed while fitting each transformer will be
printed as it is completed.
verbose_feature_names_out : bool, default=True
If True, :meth:`ColumnTransformer.get_feature_names_out` will prefix
all feature names with the name of the transformer that generated that
feature.
If False, :meth:`ColumnTransformer.get_feature_names_out` will not
prefix any feature names and will error if feature names are not
unique.
.. versionadded:: 1.0
force_int_remainder_cols : bool, default=True
This parameter has no effect.
.. note::
If you do not access the list of columns for the remainder columns
in the :attr:`ColumnTransformer.transformers_` fitted attribute,
you do not need to set this parameter.
.. versionadded:: 1.5
.. versionchanged:: 1.7
The default value for `force_int_remainder_cols` will change from
`True` to `False` in version 1.7.
.. deprecated:: 1.7
`force_int_remainder_cols` is deprecated and will be removed in version 1.9.
Returns
-------
ct : ColumnTransformer
Returns a :class:`ColumnTransformer` object.
See Also
--------
ColumnTransformer : Class that allows combining the
outputs of multiple transformer objects used on column subsets
of the data into a single feature space.
Examples
--------
>>> from sklearn.preprocessing import StandardScaler, OneHotEncoder
>>> from sklearn.compose import make_column_transformer
>>> make_column_transformer(
... (StandardScaler(), ['numerical_column']),
... (OneHotEncoder(), ['categorical_column']))
ColumnTransformer(transformers=[('standardscaler', StandardScaler(...),
['numerical_column']),
('onehotencoder', OneHotEncoder(...),
['categorical_column'])])
"""
# transformer_weights keyword is not passed through because the user
# would need to know the automatically generated names of the transformers
transformer_list = _get_transformer_list(transformers)
return ColumnTransformer(
transformer_list,
n_jobs=n_jobs,
remainder=remainder,
sparse_threshold=sparse_threshold,
verbose=verbose,
verbose_feature_names_out=verbose_feature_names_out,
force_int_remainder_cols=force_int_remainder_cols,
)
class make_column_selector:
"""Create a callable to select columns to be used with
:class:`ColumnTransformer`.
:func:`make_column_selector` can select columns based on datatype or the
columns name with a regex. When using multiple selection criteria, **all**
criteria must match for a column to be selected.
For an example of how to use :func:`make_column_selector` within a
:class:`ColumnTransformer` to select columns based on data type (i.e.
`dtype`), refer to
:ref:`sphx_glr_auto_examples_compose_plot_column_transformer_mixed_types.py`.
Parameters
----------
pattern : str, default=None
Name of columns containing this regex pattern will be included. If
None, column selection will not be selected based on pattern.
dtype_include : column dtype or list of column dtypes, default=None
A selection of dtypes to include. For more details, see
:meth:`pandas.DataFrame.select_dtypes`.
dtype_exclude : column dtype or list of column dtypes, default=None
A selection of dtypes to exclude. For more details, see
:meth:`pandas.DataFrame.select_dtypes`.
Returns
-------
selector : callable
Callable for column selection to be used by a
:class:`ColumnTransformer`.
See Also
--------
ColumnTransformer : Class that allows combining the
outputs of multiple transformer objects used on column subsets
of the data into a single feature space.
Examples
--------
>>> from sklearn.preprocessing import StandardScaler, OneHotEncoder
>>> from sklearn.compose import make_column_transformer
>>> from sklearn.compose import make_column_selector
>>> import numpy as np
>>> import pandas as pd # doctest: +SKIP
>>> X = pd.DataFrame({'city': ['London', 'London', 'Paris', 'Sallisaw'],
... 'rating': [5, 3, 4, 5]}) # doctest: +SKIP
>>> ct = make_column_transformer(
... (StandardScaler(),
... make_column_selector(dtype_include=np.number)), # rating
... (OneHotEncoder(),
... make_column_selector(dtype_include=object))) # city
>>> ct.fit_transform(X) # doctest: +SKIP
array([[ 0.90453403, 1. , 0. , 0. ],
[-1.50755672, 1. , 0. , 0. ],
[-0.30151134, 0. , 1. , 0. ],
[ 0.90453403, 0. , 0. , 1. ]])
"""
def __init__(self, pattern=None, *, dtype_include=None, dtype_exclude=None):
self.pattern = pattern
self.dtype_include = dtype_include
self.dtype_exclude = dtype_exclude
def __call__(self, df):
"""Callable for column selection to be used by a
:class:`ColumnTransformer`.
Parameters
----------
df : dataframe of shape (n_features, n_samples)
DataFrame to select columns from.
"""
if not hasattr(df, "iloc"):
raise ValueError(
"make_column_selector can only be applied to pandas dataframes"
)
df_row = df.iloc[:1]
if self.dtype_include is not None or self.dtype_exclude is not None:
df_row = df_row.select_dtypes(
include=self.dtype_include, exclude=self.dtype_exclude
)
cols = df_row.columns
if self.pattern is not None:
cols = cols[cols.str.contains(self.pattern, regex=True)]
return cols.tolist()
def _feature_names_out_with_str_format(
transformer_name: str, feature_name: str, str_format: str
) -> str:
return str_format.format(
transformer_name=transformer_name, feature_name=feature_name
)
|