|
| 1 | +import narwhals as nw |
| 2 | +from sklearn.base import BaseEstimator, TransformerMixin |
| 3 | + |
| 4 | + |
| 5 | +class SelectCols(TransformerMixin, BaseEstimator): |
| 6 | + """Select a subset of a DataFrame's columns. |
| 7 | +
|
| 8 | + A ``ValueError`` is raised if any of the provided column names are not in |
| 9 | + the dataframe. |
| 10 | +
|
| 11 | + Accepts anything accepted by :func:`narwhals.from_native(..., eager_only=True)`. |
| 12 | +
|
| 13 | + Arguments |
| 14 | + cols : list of str or str |
| 15 | + The columns to select. A single column name can be passed as a ``str``: |
| 16 | + ``"col_name"`` is the same as ``["col_name"]``. |
| 17 | +
|
| 18 | + **Usage** |
| 19 | + ```python |
| 20 | + >>> import polars as pl |
| 21 | + >>> from playtime.estimators import SelectCols |
| 22 | + >>> df = pl.DataFrame({"A": [1, 2], "B": [10, 20], "C": ["x", "y"]}) |
| 23 | + >>> df |
| 24 | + A B C |
| 25 | + 0 1 10 x |
| 26 | + 1 2 20 y |
| 27 | + >>> SelectCols(["C", "A"]).fit_transform(df) |
| 28 | + C A |
| 29 | + 0 x 1 |
| 30 | + 1 y 2 |
| 31 | + >>> SelectCols(["X", "A"]).fit_transform(df) |
| 32 | + Traceback (most recent call last): |
| 33 | + ... |
| 34 | + ValueError: The following columns are requested for selection but missing from dataframe: ['X'] |
| 35 | + ``` |
| 36 | + """ |
| 37 | + |
| 38 | + def __init__(self, cols=None): |
| 39 | + self.cols = cols |
| 40 | + |
| 41 | + def fit(self, X, y=None): |
| 42 | + """Fit the transformer. |
| 43 | +
|
| 44 | + Arguments |
| 45 | + X : DataFrame or None |
| 46 | + If `X` is a DataFrame, the transformer checks that all the column |
| 47 | + names provided in ``self.cols`` can be found in `X`. |
| 48 | +
|
| 49 | + y : None |
| 50 | + Unused. |
| 51 | +
|
| 52 | + Returns |
| 53 | + ------- |
| 54 | + SelectCols |
| 55 | + The transformer itself. |
| 56 | + """ |
| 57 | + nw.from_native(X, eager_only=True).select(self.cols) |
| 58 | + return self |
| 59 | + |
| 60 | + def transform(self, X): |
| 61 | + """Transform a dataframe by selecting columns. |
| 62 | +
|
| 63 | + Parameters |
| 64 | + ---------- |
| 65 | + X : DataFrame |
| 66 | + The DataFrame on which to apply the selection. |
| 67 | +
|
| 68 | + Returns |
| 69 | + ------- |
| 70 | + DataFrame |
| 71 | + The input DataFrame ``X`` after selecting only the columns listed |
| 72 | + in ``self.cols`` (in the provided order). |
| 73 | + """ |
| 74 | + return nw.from_native(X, eager_only=True).select(self.cols) |
0 commit comments