pax_global_header00006660000000000000000000000064142100013030014472gustar00rootroot0000000000000052 comment=f38d6ad346862c78b63b5e7f786a0556aa69b33c sklearn-pandas-2.2.0/000077500000000000000000000000001421000130300143765ustar00rootroot00000000000000sklearn-pandas-2.2.0/.circleci/000077500000000000000000000000001421000130300162315ustar00rootroot00000000000000sklearn-pandas-2.2.0/.circleci/config.yml000066400000000000000000000010651421000130300202230ustar00rootroot00000000000000version: 2 jobs: test37: docker: - image: circleci/python:3.7 steps: - checkout - run: pip install --user nox - run: ~/.local/bin/nox test38: docker: - image: circleci/python:3.8 steps: - checkout - run: pip install --user nox - run: ~/.local/bin/nox test39: docker: - image: cimg/python:3.9.1 steps: - checkout - run: pip install --user nox - run: ~/.local/bin/nox workflows: version: 2 build_and_test: jobs: - test37 - test39 sklearn-pandas-2.2.0/.github/000077500000000000000000000000001421000130300157365ustar00rootroot00000000000000sklearn-pandas-2.2.0/.github/workflows/000077500000000000000000000000001421000130300177735ustar00rootroot00000000000000sklearn-pandas-2.2.0/.github/workflows/step1_test.yml000066400000000000000000000014241421000130300226120ustar00rootroot00000000000000# This workflows will upload a Python Package using Twine when a release is created # For more information see: https://help.github.com/en/actions/language-and-framework-guides/using-python-with-github-actions#publishing-to-package-registries name: 1 Test Package on: workflow_dispatch: branches: - main jobs: test: runs-on: ubuntu-latest strategy: matrix: python-version: [3.7, 3.8, 3.9] steps: - uses: actions/checkout@v2 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v1 with: python-version: ${{ matrix.python-version }} - name: Install dependencies run: | python -m pip install --upgrade pip pip install nox - name: Test with pytest run: nox sklearn-pandas-2.2.0/.github/workflows/step2_release.yml000066400000000000000000000014651421000130300232610ustar00rootroot00000000000000name: 2 Release Package on: workflow_dispatch: branches: - main jobs: release: runs-on: ubuntu-latest steps: - name: Checkout Code uses: actions/checkout@v2 with: fetch-depth: 0 - name: Changelog uses: scottbrenner/generate-changelog-action@master id: Changelog - name: Create Release id: create_release uses: actions/create-release@latest env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # This token is provided by Actions, you do not need to create your own token with: tag_name: ${{ github.ref }} release_name: ${{ github.ref }} body: | ${{ steps.Changelog.outputs.changelog }} draft: false prerelease: falsesklearn-pandas-2.2.0/.github/workflows/step3_pypi_deploy.yml000066400000000000000000000014051421000130300241710ustar00rootroot00000000000000name: 3 PyPI Deploy on: workflow_dispatch: branches: - main jobs: deploy: runs-on: ubuntu-latest steps: - name: Checkout Code uses: actions/checkout@v2 with: fetch-depth: 0 - name: Set up Python uses: actions/setup-python@v2 with: python-version: "3.x" - name: Install dependencies run: | python -m pip install --upgrade pip pip install setuptools wheel twine - name: Build and publish PyPI env: TWINE_USERNAME: __token__ TWINE_PASSWORD: ${{ secrets.PYPI_PASSWORD }} run: | python setup.py sdist bdist_wheel twine upload --repository pypi dist/*sklearn-pandas-2.2.0/.github/workflows/step4_conda_deploy.yml000066400000000000000000000006531421000130300243010ustar00rootroot00000000000000name: 4 Conda Deploy on: workflow_dispatch: branches: - main jobs: conda_deploy: runs-on: ubuntu-latest # needs: test steps: - uses: actions/checkout@v2 - name: publish-to-conda uses: fcakyon/conda-publish-action@v1.3 with: subdir: 'conda' anacondatoken: ${{ secrets.ANACONDA_TOKEN }} platforms: 'win osx linux' sklearn-pandas-2.2.0/CONTRIBUTING.md000066400000000000000000000025041421000130300166300ustar00rootroot00000000000000# Contributing ## Development environment and steps 1. Click on the "Fork" button at the top-right of the GitHub page. 2. Clone your fork. Example: `git clone git@github.com:dukebody/sklearn-pandas.git`. 3. Create a new branch to work on the issue/feature you want. 4. Hack out your code. To run the tests and `flake8`, just run `nox`. Tests live in the `tests` subfolder. 5. Submit a new PR with your code, indicating in the PR which issue/feature it relates to. Note: You don't need to install `sklearn-pandas` in your virtualenv to run the tests. `tox` will automatically create multiple virtual environments to run them with multiple package versions. ## Guidelines - Remember that `sklearn-pandas` does not expect to do everything. Its scope is to serve as an integration layer between `scikit-learn` and `pandas` where needed. If the feature you want to implement adds a lot of complexity to the code, think twice if it is really needed or can be worked around in a few lines. - Always write tests for any change introduced. - If the change involves new options or modifies the public interface, modify also the `README` file explaining how to use it. It uses doctests to test the documentation itself. - If the change is not just cosmetic, add a line to the Changelog section and your name to the Credits section of the `README` file. sklearn-pandas-2.2.0/LICENSE000066400000000000000000000045461421000130300154140ustar00rootroot00000000000000sklearn-pandas -- bridge code for cross-validation of pandas data frames with sklearn This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. Paul Butler The source code of DataFrameMapper is derived from code originally written by Ben Hamner and released under the following license. Copyright (c) 2013, Ben Hamner Author: Ben Hamner (ben@benhamner.com) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. sklearn-pandas-2.2.0/MANIFEST.in000066400000000000000000000000431421000130300161310ustar00rootroot00000000000000include LICENSE include README.rst sklearn-pandas-2.2.0/README.rst000066400000000000000000000621051421000130300160710ustar00rootroot00000000000000 Sklearn-pandas ============== .. image:: https://circleci.com/gh/scikit-learn-contrib/sklearn-pandas.svg?style=svg :target: https://circleci.com/gh/scikit-learn-contrib/sklearn-pandas .. image:: https://img.shields.io/pypi/v/sklearn-pandas.svg :target: https://pypi.python.org/pypi/sklearn-pandas/ .. image:: https://anaconda.org/conda-forge/sklearn-pandas/badges/version.svg :target: https://anaconda.org/conda-forge/sklearn-pandas/ This module provides a bridge between `Scikit-Learn `__'s machine learning methods and `pandas `__-style Data Frames. In particular, it provides a way to map ``DataFrame`` columns to transformations, which are later recombined into features. Installation ------------ You can install ``sklearn-pandas`` with ``pip``:: # pip install sklearn-pandas or conda-forge:: # conda install -c conda-forge sklearn-pandas Tests ----- The examples in this file double as basic sanity tests. To run them, use ``doctest``, which is included with python:: # python -m doctest README.rst Usage ----- Import ****** Import what you need from the ``sklearn_pandas`` package. The choices are: * ``DataFrameMapper``, a class for mapping pandas data frame columns to different sklearn transformations For this demonstration, we will import both:: >>> from sklearn_pandas import DataFrameMapper For these examples, we'll also use pandas, numpy, and sklearn:: >>> import pandas as pd >>> import numpy as np >>> import sklearn.preprocessing, sklearn.decomposition, \ ... sklearn.linear_model, sklearn.pipeline, sklearn.metrics, \ ... sklearn.compose >>> from sklearn.feature_extraction.text import CountVectorizer Load some Data ************** Normally you'll read the data from a file, but for demonstration purposes we'll create a data frame from a Python dict:: >>> data = pd.DataFrame({'pet': ['cat', 'dog', 'dog', 'fish', 'cat', 'dog', 'cat', 'fish'], ... 'children': [4., 6, 3, 3, 2, 3, 5, 4], ... 'salary': [90., 24, 44, 27, 32, 59, 36, 27]}) Transformation Mapping ---------------------- Map the Columns to Transformations ********************************** The mapper takes a list of tuples. Each tuple has three elements: 1. column name(s): The first element is a column name from the pandas DataFrame, or a list containing one or multiple columns (we will see an example with multiple columns later) or an instance of a callable function such as `make_column_selector `__. 2. transformer(s): The second element is an object which will perform the transformation which will be applied to that column. 3. attributes: The third one is optional and is a dictionary containing the transformation options, if applicable (see "custom column names for transformed features" below). Let's see an example:: >>> mapper = DataFrameMapper([ ... ('pet', sklearn.preprocessing.LabelBinarizer()), ... (['children'], sklearn.preprocessing.StandardScaler()) ... ]) The difference between specifying the column selector as ``'column'`` (as a simple string) and ``['column']`` (as a list with one element) is the shape of the array that is passed to the transformer. In the first case, a one dimensional array will be passed, while in the second case it will be a 2-dimensional array with one column, i.e. a column vector. This behaviour mimics the same pattern as pandas' dataframes ``__getitem__`` indexing: >>> data['children'].shape (8,) >>> data[['children']].shape (8, 1) Be aware that some transformers expect a 1-dimensional input (the label-oriented ones) while some others, like ``OneHotEncoder`` or ``Imputer``, expect 2-dimensional input, with the shape ``[n_samples, n_features]``. Test the Transformation *********************** We can use the ``fit_transform`` shortcut to both fit the model and see what transformed data looks like. In this and the other examples, output is rounded to two digits with ``np.round`` to account for rounding errors on different hardware:: >>> np.round(mapper.fit_transform(data.copy()), 2) array([[ 1. , 0. , 0. , 0.21], [ 0. , 1. , 0. , 1.88], [ 0. , 1. , 0. , -0.63], [ 0. , 0. , 1. , -0.63], [ 1. , 0. , 0. , -1.46], [ 0. , 1. , 0. , -0.63], [ 1. , 0. , 0. , 1.04], [ 0. , 0. , 1. , 0.21]]) Note that the first three columns are the output of the ``LabelBinarizer`` (corresponding to ``cat``, ``dog``, and ``fish`` respectively) and the fourth column is the standardized value for the number of children. In general, the columns are ordered according to the order given when the ``DataFrameMapper`` is constructed. Now that the transformation is trained, we confirm that it works on new data:: >>> sample = pd.DataFrame({'pet': ['cat'], 'children': [5.]}) >>> np.round(mapper.transform(sample), 2) array([[1. , 0. , 0. , 1.04]]) Output features names ********************* In certain cases, like when studying the feature importances for some model, we want to be able to associate the original features to the ones generated by the dataframe mapper. We can do so by inspecting the automatically generated ``transformed_names_`` attribute of the mapper after transformation:: >>> mapper.transformed_names_ ['pet_cat', 'pet_dog', 'pet_fish', 'children'] Custom column names for transformed features ******************************************** We can provide a custom name for the transformed features, to be used instead of the automatically generated one, by specifying it as the third argument of the feature definition:: >>> mapper_alias = DataFrameMapper([ ... (['children'], sklearn.preprocessing.StandardScaler(), ... {'alias': 'children_scaled'}) ... ]) >>> _ = mapper_alias.fit_transform(data.copy()) >>> mapper_alias.transformed_names_ ['children_scaled'] Alternatively, you can also specify prefix and/or suffix to add to the column name. For example:: >>> mapper_alias = DataFrameMapper([ ... (['children'], sklearn.preprocessing.StandardScaler(), {'prefix': 'standard_scaled_'}), ... (['children'], sklearn.preprocessing.StandardScaler(), {'suffix': '_raw'}) ... ]) >>> _ = mapper_alias.fit_transform(data.copy()) >>> mapper_alias.transformed_names_ ['standard_scaled_children', 'children_raw'] Dynamic Columns *********************** In some situations the columns are not known before hand and we would like to dynamically select them during the fit operation. As shown below, in such situations you can provide either a custom callable or use `make_column_selector `__. >>> class GetColumnsStartingWith: ... def __init__(self, start_str): ... self.pattern = start_str ... ... def __call__(self, X:pd.DataFrame=None): ... return [c for c in X.columns if c.startswith(self.pattern)] ... >>> df = pd.DataFrame({ ... 'sepal length (cm)': [1.0, 2.0, 3.0], ... 'sepal width (cm)': [1.0, 2.0, 3.0], ... 'petal length (cm)': [1.0, 2.0, 3.0], ... 'petal width (cm)': [1.0, 2.0, 3.0] ... }) >>> t = DataFrameMapper([ ... ( ... sklearn.compose.make_column_selector(dtype_include=float), ... sklearn.preprocessing.StandardScaler(), ... {'alias': 'x'} ... ), ... ( ... GetColumnsStartingWith('petal'), ... None, ... {'alias': 'petal'} ... )], df_out=True, default=False) >>> t.fit(df).transform(df).shape (3, 6) >>> t.transformed_names_ ['x_0', 'x_1', 'x_2', 'x_3', 'petal_0', 'petal_1'] Above we use `make_column_selector` to select all columns that are of type float and also use a custom callable function to select columns that start with the word 'petal'. Passing Series/DataFrames to the transformers ********************************************* By default the transformers are passed a numpy array of the selected columns as input. This is because ``sklearn`` transformers are historically designed to work with numpy arrays, not with pandas dataframes, even though their basic indexing interfaces are similar. However we can pass a dataframe/series to the transformers to handle custom cases initializing the dataframe mapper with ``input_df=True``:: >>> from sklearn.base import TransformerMixin >>> class DateEncoder(TransformerMixin): ... def fit(self, X, y=None): ... return self ... ... def transform(self, X): ... dt = X.dt ... return pd.concat([dt.year, dt.month, dt.day], axis=1) >>> dates_df = pd.DataFrame( ... {'dates': pd.date_range('2015-10-30', '2015-11-02')}) >>> mapper_dates = DataFrameMapper([ ... ('dates', DateEncoder()) ... ], input_df=True) >>> mapper_dates.fit_transform(dates_df) array([[2015, 10, 30], [2015, 10, 31], [2015, 11, 1], [2015, 11, 2]]) We can also specify this option per group of columns instead of for the whole mapper:: >>> mapper_dates = DataFrameMapper([ ... ('dates', DateEncoder(), {'input_df': True}) ... ]) >>> mapper_dates.fit_transform(dates_df) array([[2015, 10, 30], [2015, 10, 31], [2015, 11, 1], [2015, 11, 2]]) Outputting a dataframe ********************** By default the output of the dataframe mapper is a numpy array. This is so because most sklearn estimators expect a numpy array as input. If however we want the output of the mapper to be a dataframe, we can do so using the parameter ``df_out`` when creating the mapper:: >>> mapper_df = DataFrameMapper([ ... ('pet', sklearn.preprocessing.LabelBinarizer()), ... (['children'], sklearn.preprocessing.StandardScaler()) ... ], df_out=True) >>> np.round(mapper_df.fit_transform(data.copy()), 2) pet_cat pet_dog pet_fish children 0 1 0 0 0.21 1 0 1 0 1.88 2 0 1 0 -0.63 3 0 0 1 -0.63 4 1 0 0 -1.46 5 0 1 0 -0.63 6 1 0 0 1.04 7 0 0 1 0.21 The names for the columns are the same ones present in the ``transformed_names_`` attribute. Note this does not work together with the ``default=True`` or ``sparse=True`` arguments to the mapper. Dropping columns explictly ******************************* Sometimes it is required to drop a specific column/ list of columns. For this purpose, ``drop_cols`` argument for ``DataFrameMapper`` can be used. Default value is ``None`` >>> mapper_df = DataFrameMapper([ ... ('pet', sklearn.preprocessing.LabelBinarizer()), ... (['children'], sklearn.preprocessing.StandardScaler()) ... ], drop_cols=['salary']) Now running ``fit_transform`` will run transformations on 'pet' and 'children' and drop 'salary' column: >>> np.round(mapper_df.fit_transform(data.copy()), 1) array([[ 1. , 0. , 0. , 0.2], [ 0. , 1. , 0. , 1.9], [ 0. , 1. , 0. , -0.6], [ 0. , 0. , 1. , -0.6], [ 1. , 0. , 0. , -1.5], [ 0. , 1. , 0. , -0.6], [ 1. , 0. , 0. , 1. ], [ 0. , 0. , 1. , 0.2]]) Transformations may require multiple input columns. In these Transform Multiple Columns ************************** Transformations may require multiple input columns. In these cases, the column names can be specified in a list:: >>> mapper2 = DataFrameMapper([ ... (['children', 'salary'], sklearn.decomposition.PCA(1)) ... ]) Now running ``fit_transform`` will run PCA on the ``children`` and ``salary`` columns and return the first principal component:: >>> np.round(mapper2.fit_transform(data.copy()), 1) array([[ 47.6], [-18.4], [ 1.6], [-15.4], [-10.4], [ 16.6], [ -6.4], [-15.4]]) Multiple transformers for the same column ***************************************** Multiple transformers can be applied to the same column specifying them in a list:: >>> from sklearn.impute import SimpleImputer >>> mapper3 = DataFrameMapper([ ... (['age'], [SimpleImputer(), ... sklearn.preprocessing.StandardScaler()])]) >>> data_3 = pd.DataFrame({'age': [1, np.nan, 3]}) >>> mapper3.fit_transform(data_3) array([[-1.22474487], [ 0. ], [ 1.22474487]]) Columns that don't need any transformation ****************************************** Only columns that are listed in the DataFrameMapper are kept. To keep a column but don't apply any transformation to it, use `None` as transformer:: >>> mapper3 = DataFrameMapper([ ... ('pet', sklearn.preprocessing.LabelBinarizer()), ... ('children', None) ... ]) >>> np.round(mapper3.fit_transform(data.copy())) array([[1., 0., 0., 4.], [0., 1., 0., 6.], [0., 1., 0., 3.], [0., 0., 1., 3.], [1., 0., 0., 2.], [0., 1., 0., 3.], [1., 0., 0., 5.], [0., 0., 1., 4.]]) Applying a default transformer ****************************** A default transformer can be applied to columns not explicitly selected passing it as the ``default`` argument to the mapper: >>> mapper4 = DataFrameMapper([ ... ('pet', sklearn.preprocessing.LabelBinarizer()), ... ('children', None) ... ], default=sklearn.preprocessing.StandardScaler()) >>> np.round(mapper4.fit_transform(data.copy()), 1) array([[ 1. , 0. , 0. , 4. , 2.3], [ 0. , 1. , 0. , 6. , -0.9], [ 0. , 1. , 0. , 3. , 0.1], [ 0. , 0. , 1. , 3. , -0.7], [ 1. , 0. , 0. , 2. , -0.5], [ 0. , 1. , 0. , 3. , 0.8], [ 1. , 0. , 0. , 5. , -0.3], [ 0. , 0. , 1. , 4. , -0.7]]) Using ``default=False`` (the default) drops unselected columns. Using ``default=None`` pass the unselected columns unchanged. Same transformer for the multiple columns ***************************************** Sometimes it is required to apply the same transformation to several dataframe columns. To simplify this process, the package provides ``gen_features`` function which accepts a list of columns and feature transformer class (or list of classes), and generates a feature definition, acceptable by ``DataFrameMapper``. For example, consider a dataset with three categorical columns, 'col1', 'col2', and 'col3', To binarize each of them, one could pass column names and ``LabelBinarizer`` transformer class into generator, and then use returned definition as ``features`` argument for ``DataFrameMapper``: >>> from sklearn_pandas import gen_features >>> feature_def = gen_features( ... columns=['col1', 'col2', 'col3'], ... classes=[sklearn.preprocessing.LabelEncoder] ... ) >>> feature_def [('col1', [LabelEncoder()], {}), ('col2', [LabelEncoder()], {}), ('col3', [LabelEncoder()], {})] >>> mapper5 = DataFrameMapper(feature_def) >>> data5 = pd.DataFrame({ ... 'col1': ['yes', 'no', 'yes'], ... 'col2': [True, False, False], ... 'col3': ['one', 'two', 'three'] ... }) >>> mapper5.fit_transform(data5) array([[1, 1, 0], [0, 0, 2], [1, 0, 1]]) If it is required to override some of transformer parameters, then a dict with 'class' key and transformer parameters should be provided. For example, consider a dataset with missing values. Then the following code could be used to override default imputing strategy: >>> from sklearn.impute import SimpleImputer >>> import numpy as np >>> feature_def = gen_features( ... columns=[['col1'], ['col2'], ['col3']], ... classes=[{'class': SimpleImputer, 'strategy':'most_frequent'}] ... ) >>> mapper6 = DataFrameMapper(feature_def) >>> data6 = pd.DataFrame({ ... 'col1': [np.nan, 1, 1, 2, 3], ... 'col2': [True, False, np.nan, np.nan, True], ... 'col3': [0, 0, 0, np.nan, np.nan] ... }) >>> mapper6.fit_transform(data6) array([[1.0, True, 0.0], [1.0, False, 0.0], [1.0, True, 0.0], [2.0, True, 0.0], [3.0, True, 0.0]], dtype=object) You can also specify global prefix or suffix for the generated transformed column names using the prefix and suffix parameters:: >>> feature_def = gen_features( ... columns=['col1', 'col2', 'col3'], ... classes=[sklearn.preprocessing.LabelEncoder], ... prefix="lblencoder_" ... ) >>> mapper5 = DataFrameMapper(feature_def) >>> data5 = pd.DataFrame({ ... 'col1': ['yes', 'no', 'yes'], ... 'col2': [True, False, False], ... 'col3': ['one', 'two', 'three'] ... }) >>> _ = mapper5.fit_transform(data5) >>> mapper5.transformed_names_ ['lblencoder_col1', 'lblencoder_col2', 'lblencoder_col3'] Feature selection and other supervised transformations ****************************************************** ``DataFrameMapper`` supports transformers that require both X and y arguments. An example of this is feature selection. Treating the 'pet' column as the target, we will select the column that best predicts it. >>> from sklearn.feature_selection import SelectKBest, chi2 >>> mapper_fs = DataFrameMapper([(['children','salary'], SelectKBest(chi2, k=1))]) >>> mapper_fs.fit_transform(data[['children','salary']], data['pet']) array([[90.], [24.], [44.], [27.], [32.], [59.], [36.], [27.]]) Working with sparse features **************************** A ``DataFrameMapper`` will return a dense feature array by default. Setting ``sparse=True`` in the mapper will return a sparse array whenever any of the extracted features is sparse. Example: >>> mapper5 = DataFrameMapper([ ... ('pet', CountVectorizer()), ... ], sparse=True) >>> type(mapper5.fit_transform(data)) The stacking of the sparse features is done without ever densifying them. Using ``NumericalTransformer`` *********************************** While you can use ``FunctionTransformation`` to generate arbitrary transformers, it can present serialization issues when pickling. Use ``NumericalTransformer`` instead, which takes the function name as a string parameter and hence can be easily serialized. >>> from sklearn_pandas import NumericalTransformer >>> mapper5 = DataFrameMapper([ ... ('children', NumericalTransformer('log')), ... ]) >>> mapper5.fit_transform(data) array([[1.38629436], [1.79175947], [1.09861229], [1.09861229], [0.69314718], [1.09861229], [1.60943791], [1.38629436]]) Changing Logging level *********************************** You can change log level to info to print time take to fit/transform features. Setting it to higher level will stop printing elapsed time. Below example shows how to change logging level. >>> import logging >>> logging.getLogger('sklearn_pandas').setLevel(logging.INFO) Changelog --------- 2.2.0 (2021-05-07) ****************** * Added an ability to provide callable functions instead of static column list. 2.1.0 (2021-02-26) ****************** * Removed test for Python 3.6 and added Python 3.9 * Added deprecation warning for NumericalTransformer * Fixed pickling issue causing integration issues with Baikal. * Started publishing package to conda repo 2.0.4 (2020-11-06) ****************** * Explicitly handling serialization (#224) * document fixes * Making transform function thread safe (#194) * Switched to nox for unit testing (#226) 2.0.3 (2020-11-06) ****************** * Added elapsed time information for each feature. 2.0.2 (2020-10-01) ****************** * Fix `DataFrameMapper` drop_cols attribute naming consistency with scikit-learn and initialization. 2.0.1 (2020-09-07) ****************** * Added an option to explicitly drop columns. 2.0.0 (2020-08-01) ****************** * Deprecated support for Python < 3.6. * Deprecated support for old versions of scikit-learn, pandas and numpy. Please check setup.py for minimum requirement. * Removed CategoricalImputer, cross_val_score and GridSearchCV. All these functionality now exists as part of scikit-learn. Please use SimpleImputer instead of CategoricalImputer. Also Cross validation from sklearn now supports dataframe so we don't need to use cross validation wrapper provided over here. * Added ``NumericalTransformer`` for common numerical transformations. Currently it implements log and log1p transformation. * Added prefix and suffix options. See examples above. These are usually helpful when using gen_features. * Added ``drop_cols`` argument to DataframeMapper. This can be used to explicitly drop columns 1.8.0 (2018-12-01) ****************** * Add ``FunctionTransformer`` class (#117). * Fix column names derivation for dataframes with multi-index or non-string columns (#166). * Change behaviour of DataFrameMapper's fit_transform method to invoke each underlying transformers' native fit_transform if implemented (#150). 1.7.0 (2018-08-15) ****************** * Fix issues with unicode names in ``get_names`` (#160). * Update to build using ``numpy==1.14`` and ``python==3.6`` (#154). * Add ``strategy`` and ``fill_value`` parameters to ``CategoricalImputer`` to allow imputing with values other than the mode (#144),(#161). * Preserve input data types when no transform is supplied (#138). 1.6.0 (2017-10-28) ****************** * Add column name to exception during fit/transform (#110). * Add ``gen_feature`` helper function to help generating the same transformation for multiple columns (#126). 1.5.0 (2017-06-24) ****************** * Allow inputting a dataframe/series per group of columns. * Get feature names also from ``estimator.get_feature_names()`` if present. * Attempt to derive feature names from individual transformers when applying a list of transformers. * Do not mutate features in ``__init__`` to be compatible with ``sklearn>=0.20`` (#76). 1.4.0 (2017-05-13) ****************** * Allow specifying a custom name (alias) for transformed columns (#83). * Capture output columns generated names in ``transformed_names_`` attribute (#78). * Add ``CategoricalImputer`` that replaces null-like values with the mode for string-like columns. * Add ``input_df`` init argument to allow inputting a dataframe/series to the transformers instead of a numpy array (#60). 1.3.0 (2017-01-21) ****************** * Make the mapper return dataframes when ``df_out=True`` (#70, #74). * Update imports to avoid deprecation warnings in sklearn 0.18 (#68). 1.2.0 (2016-10-02) ****************** * Deprecate custom cross-validation shim classes. * Require ``scikit-learn>=0.15.0``. Resolves #49. * Allow applying a default transformer to columns not selected explicitly in the mapper. Resolves #55. * Allow specifying an optional ``y`` argument during transform for supervised transformations. Resolves #58. 1.1.0 (2015-12-06) ******************* * Delete obsolete ``PassThroughTransformer``. If no transformation is desired for a given column, use ``None`` as transformer. * Factor out code in several modules, to avoid having everything in ``__init__.py``. * Use custom ``TransformerPipeline`` class to allow transformation steps accepting only a X argument. Fixes #46. * Add compatibility shim for unpickling mappers with list of transformers created before 1.0.0. Fixes #45. 1.0.0 (2015-11-28) ******************* * Change version numbering scheme to SemVer. * Use ``sklearn.pipeline.Pipeline`` instead of copying its code. Resolves #43. * Raise ``KeyError`` when selecting unexistent columns in the dataframe. Fixes #30. * Return sparse feature array if any of the features is sparse and ``sparse`` argument is ``True``. Defaults to ``False`` to avoid potential breaking of existing code. Resolves #34. * Return model and prediction in custom CV classes. Fixes #27. 0.0.12 (2015-11-07) ******************** * Allow specifying a list of transformers to use sequentially on the same column. Credits ------- The code for ``DataFrameMapper`` is based on code originally written by `Ben Hamner `__. Other contributors: * Ariel Rossanigo (@arielrossanigo) * Arnau Gil Amat (@arnau126) * Assaf Ben-David (@AssafBenDavid) * Brendan Herger (@bjherger) * Cal Paterson (@calpaterson) * @defvorfu * Floris Hoogenboom (@FlorisHoogenboom) * Gustavo Sena Mafra (@gsmafra) * Israel Saeta Pérez (@dukebody) * Jeremy Howard (@jph00) * Jimmy Wan (@jimmywan) * Kristof Van Engeland (@kristofve91) * Olivier Grisel (@ogrisel) * Paul Butler (@paulgb) * Richard Miller (@rwjmiller) * Ritesh Agrawal (@ragrawal) * @SandroCasagrande * Timothy Sweetser (@hacktuarial) * Vitaley Zaretskey (@vzaretsk) * Zac Stewart (@zacstewart) * Parul Singh (@paro1234) * Vincent Heusinkveld (@VHeusinkveld) sklearn-pandas-2.2.0/conda/000077500000000000000000000000001421000130300154625ustar00rootroot00000000000000sklearn-pandas-2.2.0/conda/conda_build_config.yml000066400000000000000000000000461421000130300217750ustar00rootroot00000000000000python: - 3.7 - 3.8 - 3.9 sklearn-pandas-2.2.0/conda/meta.yaml000066400000000000000000000011351421000130300172740ustar00rootroot00000000000000{% set data = load_setup_py_data() %} package: name: sklearn-pandas version: {{ data['version'] }} source: path: .. build: number: 0 script: python setup.py install --single-version-externally-managed --record=record.txt requirements: build: - python - scikit-learn>=0.23.0 - scipy>=1.5.1 - pandas>=1.1.4 - numpy>=1.18.1 run: - python - scikit-learn>=0.23.0 - scipy>=1.5.1 - pandas>=1.1.4 - numpy>=1.18.1 test: imports: - sklearn_pandas about: home: {{ data['url'] }} license: {{ data['license'] }} summary: {{ data['description'] }}sklearn-pandas-2.2.0/nox.ini000066400000000000000000000002341421000130300157020ustar00rootroot00000000000000[flake8] exclude = .git .github __pycache__ build dist *site-packages/ *bin/ *.egg/* .eggs .tox docssklearn-pandas-2.2.0/noxfile.py000066400000000000000000000014711421000130300164170ustar00rootroot00000000000000import nox @nox.session def lint(session): session.install('pytest>=5.3.5', 'setuptools>=45.2', 'wheel>=0.34.2', 'flake8>=3.7.9', 'numpy==1.18.1', 'pandas==1.1.4') session.install('.') session.run('flake8', 'sklearn_pandas/', 'tests') @nox.session @nox.parametrize('numpy', ['1.18.1', '1.19.4', '1.20.1']) @nox.parametrize('scipy', ['1.5.4', '1.6.0']) @nox.parametrize('pandas', ['1.1.4', '1.2.2']) def tests(session, numpy, scipy, pandas): session.install('pytest>=5.3.5', 'setuptools>=45.2', 'wheel>=0.34.2', f'numpy=={numpy}', f'scipy=={scipy}', f'pandas=={pandas}' ) session.install('.') session.run('py.test', 'README.rst', 'tests') sklearn-pandas-2.2.0/pytest.ini000066400000000000000000000000511421000130300164230ustar00rootroot00000000000000[pytest] addopts = --doctest-glob='*.rst'sklearn-pandas-2.2.0/setup.cfg000066400000000000000000000000271421000130300162160ustar00rootroot00000000000000[wheel] universal = 1 sklearn-pandas-2.2.0/setup.py000066400000000000000000000025151421000130300161130ustar00rootroot00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup from setuptools.command.test import test as TestCommand import re for line in open('sklearn_pandas/__init__.py'): match = re.match("__version__ *= *'(.*)'", line) if match: __version__, = match.groups() class PyTest(TestCommand): user_options = [('pytest-args=', 'a', "Arguments to pass to py.test")] def initialize_options(self): TestCommand.initialize_options(self) self.pytest_args = [] def finalize_options(self): TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True def run(self): import pytest errno = pytest.main(self.pytest_args) raise SystemExit(errno) setup(name='sklearn-pandas', version=__version__, description='Pandas integration with sklearn', maintainer='Ritesh Agrawal', maintainer_email='ragrawal@gmail.com', url='https://github.com/scikit-learn-contrib/sklearn-pandas', packages=['sklearn_pandas'], keywords=['scikit', 'sklearn', 'pandas'], install_requires=[ 'scikit-learn>=0.23.0', 'scipy>=1.5.1', 'pandas>=1.1.4', 'numpy>=1.18.1' ], tests_require=['pytest', 'mock'], cmdclass={'test': PyTest}, license='MIT License' ) sklearn-pandas-2.2.0/sklearn_pandas/000077500000000000000000000000001421000130300173635ustar00rootroot00000000000000sklearn-pandas-2.2.0/sklearn_pandas/__init__.py000066400000000000000000000003551421000130300214770ustar00rootroot00000000000000__version__ = '2.2.0' import logging logger = logging.getLogger(__name__) from .dataframe_mapper import DataFrameMapper # NOQA from .features_generator import gen_features # NOQA from .transformers import NumericalTransformer # NOQA sklearn-pandas-2.2.0/sklearn_pandas/cross_validation.py000066400000000000000000000003031421000130300232740ustar00rootroot00000000000000class DataWrapper(object): def __init__(self, df): self.df = df def __len__(self): return len(self.df) def __getitem__(self, key): return self.df.iloc[key] sklearn-pandas-2.2.0/sklearn_pandas/dataframe_mapper.py000066400000000000000000000400741421000130300232320ustar00rootroot00000000000000import contextlib from datetime import datetime import pandas as pd import numpy as np from scipy import sparse from sklearn.base import BaseEstimator, TransformerMixin from .cross_validation import DataWrapper from .pipeline import make_transformer_pipeline, _call_fit, TransformerPipeline from . import logger string_types = text_type = str def _handle_feature(fea): """ Convert 1-dimensional arrays to 2-dimensional column vectors. """ if len(fea.shape) == 1: fea = np.array([fea]).T return fea def _build_transformer(transformers): if isinstance(transformers, list): transformers = make_transformer_pipeline(*transformers) return transformers def _build_feature(columns, transformers, options={}, X=None): if X is None: return (columns, _build_transformer(transformers), options) return ( columns(X) if callable(columns) else columns, _build_transformer(transformers), options ) def _elapsed_secs(t1): return (datetime.now()-t1).total_seconds() def _get_feature_names(estimator): """ Attempt to extract feature names based on a given estimator """ if hasattr(estimator, 'classes_'): return estimator.classes_ elif hasattr(estimator, 'get_feature_names'): return estimator.get_feature_names() return None @contextlib.contextmanager def add_column_names_to_exception(column_names): # Stolen from https://stackoverflow.com/a/17677938/356729 try: yield except Exception as ex: if ex.args: msg = u'{}: {}'.format(column_names, ex.args[0]) else: msg = text_type(column_names) ex.args = (msg,) + ex.args[1:] raise class DataFrameMapper(BaseEstimator, TransformerMixin): """ Map Pandas data frame column subsets to their own sklearn transformation. """ def __init__(self, features, default=False, sparse=False, df_out=False, input_df=False, drop_cols=None): """ Params: features a list of tuples with features definitions. The first element is the pandas column selector. This can be a string (for one column) or a list of strings. The second element is an object that supports sklearn's transform interface, or a list of such objects The third element is optional and, if present, must be a dictionary with the options to apply to the transformation. Example: {'alias': 'day_of_week'} default default transformer to apply to the columns not explicitly selected in the mapper. If False (default), discard them. If None, pass them through untouched. Any other transformer will be applied to all the unselected columns as a whole, taken as a 2d-array. sparse will return sparse matrix if set True and any of the extracted features is sparse. Defaults to False. df_out return a pandas data frame, with each column named using the pandas column that created it (if there's only one input and output) or the input columns joined with '_' if there's multiple inputs, and the name concatenated with '_1', '_2' etc if there's multiple outputs. NB: does not work if *default* or *sparse* are true input_df If ``True`` pass the selected columns to the transformers as a pandas DataFrame or Series. Otherwise pass them as a numpy array. Defaults to ``False``. drop_cols List of columns to be dropped. Defaults to None. """ self.features = features self.default = default self.built_default = None self.sparse = sparse self.df_out = df_out self.input_df = input_df self.drop_cols = [] if drop_cols is None else drop_cols self.transformed_names_ = [] if (df_out and (sparse or default)): raise ValueError("Can not use df_out with sparse or default") def _build(self, X=None): """ Build attributes built_features and built_default. """ if isinstance(self.features, list): self.built_features = [ _build_feature(*f, X=X) for f in self.features ] else: self.built_features = _build_feature(*self.features, X=X) self.built_default = _build_transformer(self.default) @property def _selected_columns(self): """ Return a set of selected columns in the feature list. """ selected_columns = set() for feature in self.features: columns = feature[0] if isinstance(columns, list): selected_columns = selected_columns.union(set(columns)) else: selected_columns.add(columns) return selected_columns def _unselected_columns(self, X): """ Return list of columns present in X and not selected explicitly in the mapper. Unselected columns are returned in the order they appear in the dataframe to avoid issues with different ordering during default fit and transform steps. """ X_columns = list(X.columns) return [column for column in X_columns if column not in self._selected_columns and column not in self.drop_cols] def __setstate__(self, state): # compatibility for older versions of sklearn-pandas super().__setstate__(state) self.features = [_build_feature(*feat) for feat in state['features']] self.sparse = state.get('sparse', False) self.default = state.get('default', False) self.df_out = state.get('df_out', False) self.input_df = state.get('input_df', False) self.drop_cols = state.get('drop_cols', []) self.built_features = state.get('built_features', self.features) self.built_default = state.get('built_default', self.default) self.transformed_names_ = state.get('transformed_names_', []) def __getstate__(self): state = super().__getstate__() state['features'] = self.features state['sparse'] = self.sparse state['default'] = self.default state['df_out'] = self.df_out state['input_df'] = self.input_df state['drop_cols'] = self.drop_cols state['build_features'] = getattr(self, 'built_features', None) state['built_default'] = self.built_default state['transformed_names_'] = self.transformed_names_ return state def _get_col_subset(self, X, cols, input_df=False): """ Get a subset of columns from the given table X. X a Pandas dataframe; the table to select columns from cols a string or list of strings representing the columns to select. It can also be a callable that returns True or False, i.e. compatible with the built-in filter function. Returns a numpy array with the data from the selected columns """ if isinstance(cols, string_types): return_vector = True cols = [cols] else: return_vector = False # Needed when using the cross-validation compatibility # layer for sklearn<0.16.0. # Will be dropped on sklearn-pandas 2.0. if isinstance(X, list): X = [x[cols] for x in X] X = pd.DataFrame(X) elif isinstance(X, DataWrapper): X = X.df # fetch underlying data if return_vector: t = X[cols[0]] else: t = X[cols] # return either a DataFrame/Series or a numpy array if input_df: return t else: return t.values def fit(self, X, y=None): """ Fit a transformation from the pipeline X the data to fit y the target vector relative to X, optional """ self._build(X=X) for columns, transformers, options in self.built_features: t1 = datetime.now() input_df = options.get('input_df', self.input_df) if transformers is not None: with add_column_names_to_exception(columns): Xt = self._get_col_subset(X, columns, input_df) _call_fit(transformers.fit, Xt, y) logger.info(f"[FIT] {columns}: {_elapsed_secs(t1)} secs") # handle features not explicitly selected if self.built_default: # not False and not None unsel_cols = self._unselected_columns(X) with add_column_names_to_exception(unsel_cols): Xt = self._get_col_subset(X, unsel_cols, self.input_df) _call_fit(self.built_default.fit, Xt, y) return self def get_names(self, columns, transformer, x, alias=None, prefix='', suffix=''): """ Return verbose names for the transformed columns. columns name (or list of names) of the original column(s) transformer transformer - can be a TransformerPipeline x transformed columns (numpy.ndarray) alias base name to use for the selected columns """ if alias is not None: name = alias elif isinstance(columns, list): name = '_'.join(map(str, columns)) else: name = columns num_cols = x.shape[1] if len(x.shape) > 1 else 1 output = [] if num_cols > 1: # If there are as many columns as classes in the transformer, # infer column names from classes names. # If we are dealing with multiple transformers for these columns # attempt to extract the names from each of them, starting from the # last one if isinstance(transformer, TransformerPipeline): inverse_steps = transformer.steps[::-1] estimators = (estimator for name, estimator in inverse_steps) names_steps = (_get_feature_names(e) for e in estimators) names = next((n for n in names_steps if n is not None), None) # Otherwise use the only estimator present else: names = _get_feature_names(transformer) if names is not None and len(names) == num_cols: output = [f"{name}_{o}" for o in names] # otherwise, return name concatenated with '_1', '_2', etc. else: output = [name + '_' + str(o) for o in range(num_cols)] else: output = [name] if prefix == suffix == "": return output return ['{}{}{}'.format(prefix, x, suffix) for x in output] def get_dtypes(self, extracted): dtypes_features = [self.get_dtype(ex) for ex in extracted] return [dtype for dtype_feature in dtypes_features for dtype in dtype_feature] def get_dtype(self, ex): if isinstance(ex, np.ndarray) or sparse.issparse(ex): return [ex.dtype] * ex.shape[1] elif isinstance(ex, pd.DataFrame): return list(ex.dtypes) else: raise TypeError(type(ex)) def _transform(self, X, y=None, do_fit=False): """ Transform the given data with possibility to fit in advance. Avoids code duplication for implementation of transform and fit_transform. """ if do_fit: self._build(X=X) extracted = [] transformed_names_ = [] for columns, transformers, options in self.built_features: input_df = options.get('input_df', self.input_df) # columns could be a string or list of # strings; we don't care because pandas # will handle either. Xt = self._get_col_subset(X, columns, input_df) if transformers is not None: with add_column_names_to_exception(columns): if do_fit and hasattr(transformers, 'fit_transform'): t1 = datetime.now() Xt = _call_fit(transformers.fit_transform, Xt, y) logger.info(f"[FIT_TRANSFORM] {columns}: {_elapsed_secs(t1)} secs") # NOQA else: if do_fit: t1 = datetime.now() _call_fit(transformers.fit, Xt, y) logger.info( f"[FIT] {columns}: {_elapsed_secs(t1)} secs") t1 = datetime.now() Xt = transformers.transform(Xt) logger.info(f"[TRANSFORM] {columns}: {_elapsed_secs(t1)} secs") # NOQA extracted.append(_handle_feature(Xt)) alias = options.get('alias') prefix = options.get('prefix', '') suffix = options.get('suffix', '') transformed_names_ += self.get_names( columns, transformers, Xt, alias, prefix, suffix) # handle features not explicitly selected if self.built_default is not False: unsel_cols = self._unselected_columns(X) Xt = self._get_col_subset(X, unsel_cols, self.input_df) if self.built_default is not None: with add_column_names_to_exception(unsel_cols): if do_fit and hasattr(self.built_default, 'fit_transform'): Xt = _call_fit(self.built_default.fit_transform, Xt, y) else: if do_fit: _call_fit(self.built_default.fit, Xt, y) Xt = self.built_default.transform(Xt) transformed_names_ += self.get_names( unsel_cols, self.built_default, Xt) else: # if not applying a default transformer, # keep column names unmodified transformed_names_ += unsel_cols extracted.append(_handle_feature(Xt)) self.transformed_names_ = transformed_names_ # combine the feature outputs into one array. # at this point we lose track of which features # were created from which input columns, so it's # assumed that that doesn't matter to the model. # If any of the extracted features is sparse, combine sparsely. # Otherwise, combine as normal arrays. if any(sparse.issparse(fea) for fea in extracted): stacked = sparse.hstack(extracted).tocsr() # return a sparse matrix only if the mapper was initialized # with sparse=True if not self.sparse: stacked = stacked.toarray() else: stacked = np.hstack(extracted) if self.df_out: # if no rows were dropped preserve the original index, # otherwise use a new integer one no_rows_dropped = len(X) == len(stacked) if no_rows_dropped: index = X.index else: index = None # output different data types, if appropriate dtypes = self.get_dtypes(extracted) df_out = pd.DataFrame( stacked, columns=self.transformed_names_, index=index) # preserve types for col, dtype in zip(self.transformed_names_, dtypes): df_out[col] = df_out[col].astype(dtype) return df_out else: return stacked def transform(self, X): """ Transform the given data. Assumes that fit has already been called. X the data to transform """ return self._transform(X) def fit_transform(self, X, y=None): """ Fit a transformation from the pipeline and directly apply it to the given data. X the data to fit y the target vector relative to X, optional """ return self._transform(X, y, True) sklearn-pandas-2.2.0/sklearn_pandas/features_generator.py000066400000000000000000000042071421000130300236240ustar00rootroot00000000000000def gen_features(columns, classes=None, prefix='', suffix=''): """Generates a feature definition list which can be passed into DataFrameMapper Params: columns a list of column names to generate features for. classes a list of classes for each feature, a list of dictionaries with transformer class and init parameters, or None. If list of classes is provided, then each of them is instantiated with default arguments. Example: classes = [StandardScaler, LabelBinarizer] If list of dictionaries is provided, then each of them should have a 'class' key with transformer class. All other keys are passed into 'class' value constructor. Example: classes = [ {'class': StandardScaler, 'with_mean': False}, {'class': LabelBinarizer} }] If None value selected, then each feature left as is. prefix add prefix to transformed column names suffix add suffix to transformed column names. """ if classes is None: return [(column, None) for column in columns] feature_defs = [] for column in columns: feature_transformers = [] arguments = {} if prefix and prefix != "": arguments['prefix'] = prefix if suffix and suffix != "": arguments['suffix'] = suffix classes = [cls for cls in classes if cls is not None] if not classes: feature_defs.append((column, None, arguments)) else: for definition in classes: if isinstance(definition, dict): params = definition.copy() klass = params.pop('class') feature_transformers.append(klass(**params)) else: feature_transformers.append(definition()) if not feature_transformers: feature_transformers = None feature_defs.append((column, feature_transformers, arguments)) return feature_defs sklearn-pandas-2.2.0/sklearn_pandas/pipeline.py000066400000000000000000000067621421000130300215550ustar00rootroot00000000000000import six from sklearn.pipeline import _name_estimators, Pipeline from sklearn.utils import tosequence def _call_fit(fit_method, X, y=None, **kwargs): """ helper function, calls the fit or fit_transform method with the correct number of parameters fit_method: fit or fit_transform method of the transformer X: the data to fit y: the target vector relative to X, optional kwargs: any keyword arguments to the fit method return: the result of the fit or fit_transform method WARNING: if this function raises a TypeError exception, test the fit or fit_transform method passed to it in isolation as _call_fit will not distinguish TypeError due to incorrect number of arguments from other TypeError """ try: return fit_method(X, y, **kwargs) except TypeError: # fit takes only one argument return fit_method(X, **kwargs) class TransformerPipeline(Pipeline): """ Pipeline that expects all steps to be transformers taking a single X argument, an optional y argument, and having fit and transform methods. Code is copied from sklearn's Pipeline """ def __init__(self, steps): names, estimators = zip(*steps) if len(dict(steps)) != len(steps): raise ValueError( "Provided step names are not unique: %s" % (names,)) # shallow copy of steps self.steps = tosequence(steps) estimator = estimators[-1] for e in estimators: if (not (hasattr(e, "fit") or hasattr(e, "fit_transform")) or not hasattr(e, "transform")): raise TypeError("All steps of the chain should " "be transforms and implement fit and transform" " '%s' (type %s) doesn't)" % (e, type(e))) if not hasattr(estimator, "fit"): raise TypeError("Last step of chain should implement fit " "'%s' (type %s) doesn't)" % (estimator, type(estimator))) def _pre_transform(self, X, y=None, **fit_params): fit_params_steps = dict((step, {}) for step, _ in self.steps) for pname, pval in six.iteritems(fit_params): step, param = pname.split('__', 1) fit_params_steps[step][param] = pval Xt = X for name, transform in self.steps[:-1]: if hasattr(transform, "fit_transform"): Xt = _call_fit(transform.fit_transform, Xt, y, **fit_params_steps[name]) else: Xt = _call_fit(transform.fit, Xt, y, **fit_params_steps[name]).transform(Xt) return Xt, fit_params_steps[self.steps[-1][0]] def fit(self, X, y=None, **fit_params): Xt, fit_params = self._pre_transform(X, y, **fit_params) _call_fit(self.steps[-1][-1].fit, Xt, y, **fit_params) return self def fit_transform(self, X, y=None, **fit_params): Xt, fit_params = self._pre_transform(X, y, **fit_params) if hasattr(self.steps[-1][-1], 'fit_transform'): return _call_fit(self.steps[-1][-1].fit_transform, Xt, y, **fit_params) else: return _call_fit(self.steps[-1][-1].fit, Xt, y, **fit_params).transform(Xt) def make_transformer_pipeline(*steps): """Construct a TransformerPipeline from the given estimators. """ return TransformerPipeline(_name_estimators(steps)) sklearn-pandas-2.2.0/sklearn_pandas/transformers.py000066400000000000000000000030731421000130300224650ustar00rootroot00000000000000import numpy as np import pandas as pd from sklearn.base import TransformerMixin import warnings def _get_mask(X, value): """ Compute the boolean mask X == missing_values. """ if value == "NaN" or \ value is None or \ (isinstance(value, float) and np.isnan(value)): return pd.isnull(X) else: return X == value class NumericalTransformer(TransformerMixin): """ Provides commonly used numerical transformers. """ SUPPORTED_FUNCTIONS = ['log', 'log1p'] def __init__(self, func): """ Params func function to apply to input columns. The function will be applied to each value. Supported functions are defined in SUPPORTED_FUNCTIONS variable. Throws assertion error if the not supported. """ warnings.warn(""" NumericalTransformer will be deprecated in 3.0 version. Please use Sklearn.base.TransformerMixin to write customer transformers """, DeprecationWarning) assert func in self.SUPPORTED_FUNCTIONS, \ f"Only following func are supported: {self.SUPPORTED_FUNCTIONS}" super(NumericalTransformer, self).__init__() self.__func = func def fit(self, X, y=None): return self def transform(self, X, y=None): if self.__func == 'log1p': return np.vectorize(np.log1p)(X) elif self.__func == 'log': return np.vectorize(np.log)(X) raise ValueError(f"Invalid function name: {self.__func}") sklearn-pandas-2.2.0/test.py000066400000000000000000000015311421000130300157270ustar00rootroot00000000000000import pytest from unittest.mock import Mock import numpy as np import pandas as pd from sklearn_pandas import DataFrameMapper from sklearn.compose import make_column_selector from sklearn.preprocessing import StandardScaler class GetStartWith: def __init__(self, start_str): self.start_str = start_str def __call__(self, X: pd.DataFrame) -> list: return [c for c in X.columns if c.startswith(self.start_str)] df = pd.DataFrame({ 'sepal length (cm)': [1.0, 2.0, 3.0], 'sepal width (cm)': [1.0, 2.0, 3.0], 'petal length (cm)': [1.0, 2.0, 3.0], 'petal width (cm)': [1.0, 2.0, 3.0] }) t = DataFrameMapper([ (make_column_selector(dtype_include=float), StandardScaler(), {'alias': 'x'}), (GetStartWith('petal'), None, {'alias': 'petal'}) ], df_out=True, default=False) t.fit(df) print(t.transform(df).shape) sklearn-pandas-2.2.0/tests/000077500000000000000000000000001421000130300155405ustar00rootroot00000000000000sklearn-pandas-2.2.0/tests/test_data/000077500000000000000000000000001421000130300175105ustar00rootroot00000000000000sklearn-pandas-2.2.0/tests/test_data/cars.csv.gz000066400000000000000000002110231421000130300215730ustar00rootroot00000000000000TkUcars.csv}zHQyѕĀ5WdJ@4̕ V% Zt_ߤlCVV_B^{4;(j'9םw"l:Rw1I8*GuO*\&i_f&QݡQd!(LUk4֙eI%(U4Ye訛sTCAmXM7:OƱ.69.~'zu>9ʳ#Ǔ/#<|۝ϫ(Xp&[wHMkqd>Z*L#Es&,I8j<ɲu8 i%27[DK\Où'/rB>ӻwQifYMW5ud9Xw3I,tgo5b:Kcy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U20Q-Xxs/Z\I1]kv GJar_x6'*j0Ydb\Arlވ & 0: raise ValueError('Unknown values found.') return X - self.min @pytest.fixture def simple_dataframe(): return pd.DataFrame({'a': [1, 2, 3]}) @pytest.fixture def complex_dataframe(): return pd.DataFrame({'target': ['a', 'a', 'b', 'b', 'c', 'c'], 'feat1': [1, 2, 3, 4, 5, 6], 'feat2': [1, 2, 3, 2, 3, 4]}) @pytest.fixture def multiindex_dataframe(): """Example MultiIndex DataFrame, taken from pandas documentation """ iterables = [['bar', 'baz', 'foo', 'qux'], ['one', 'two']] index = pd.MultiIndex.from_product(iterables, names=['first', 'second']) df = pd.DataFrame(np.random.randn(10, 8), columns=index) return df @pytest.fixture def multiindex_dataframe_incomplete(multiindex_dataframe): """Example MultiIndex DataFrame with missing entries """ df = multiindex_dataframe mask_array = np.zeros(df.size) mask_array[:20] = 1 np.random.shuffle(mask_array) mask = mask_array.reshape(df.shape).astype(bool) df.mask(mask, inplace=True) return df def test_transformed_names_simple(simple_dataframe): """ Get transformed names of features in `transformed_names` attribute for simple transformation """ df = simple_dataframe mapper = DataFrameMapper([('a', None)]) mapper.fit_transform(df) assert mapper.transformed_names_ == ['a'] def test_transformed_names_binarizer(complex_dataframe): """ Get transformed names of features in `transformed_names` attribute for a transformation that multiplies the number of columns """ df = complex_dataframe mapper = DataFrameMapper([('target', LabelBinarizer())]) mapper.fit_transform(df) assert mapper.transformed_names_ == ['target_a', 'target_b', 'target_c'] def test_logging(caplog, complex_dataframe): """ Get transformed names of features in `transformed_names` attribute for a transformation that multiplies the number of columns """ import logging logger = logging.getLogger('sklearn_pandas') logger.setLevel(logging.INFO) df = complex_dataframe mapper = DataFrameMapper([('target', LabelBinarizer())]) mapper.fit_transform(df) assert '[FIT_TRANSFORM] target:' in caplog.text def test_transformed_names_binarizer_unicode(): df = pd.DataFrame({'target': [u'ñ', u'á', u'é']}) mapper = DataFrameMapper([('target', LabelBinarizer())]) mapper.fit_transform(df) expected_names = {u'target_ñ', u'target_á', u'target_é'} assert set(mapper.transformed_names_) == expected_names def test_transformed_names_transformers_list(complex_dataframe): """ When using a list of transformers, use them in inverse order to get the transformed names """ df = complex_dataframe mapper = DataFrameMapper([ ('target', [LabelBinarizer(), MockXTransformer()]) ]) mapper.fit_transform(df) assert mapper.transformed_names_ == ['target_a', 'target_b', 'target_c'] def test_transformed_names_simple_alias(simple_dataframe): """ If we specify an alias for a single output column, it is used for the output """ df = simple_dataframe mapper = DataFrameMapper([('a', None, {'alias': 'new_name'})]) mapper.fit_transform(df) assert mapper.transformed_names_ == ['new_name'] def test_transformed_names_complex_alias(complex_dataframe): """ If we specify an alias for a multiple output column, it is used for the output """ df = complex_dataframe mapper = DataFrameMapper([('target', LabelBinarizer(), {'alias': 'new'})]) mapper.fit_transform(df) assert mapper.transformed_names_ == ['new_a', 'new_b', 'new_c'] def test_exception_column_context_transform(simple_dataframe): """ If an exception is raised when transforming a column, the exception includes the name of the column being transformed """ class FailingTransformer(object): def fit(self, X): pass def transform(self, X): raise Exception('Some exception') df = simple_dataframe mapper = DataFrameMapper([('a', FailingTransformer())]) mapper.fit(df) with pytest.raises(Exception, match='a: Some exception'): mapper.transform(df) def test_exception_column_context_fit(simple_dataframe): """ If an exception is raised when fit a column, the exception includes the name of the column being fitted """ class FailingFitter(object): def fit(self, X): raise Exception('Some exception') df = simple_dataframe mapper = DataFrameMapper([('a', FailingFitter())]) with pytest.raises(Exception, match='a: Some exception'): mapper.fit(df) def test_simple_df(simple_dataframe): """ Get a dataframe from a simple mapped dataframe """ df = simple_dataframe mapper = DataFrameMapper([('a', None)], df_out=True) transformed = mapper.fit_transform(df) assert type(transformed) == pd.DataFrame assert len(transformed["a"]) == len(simple_dataframe["a"]) def test_complex_df(complex_dataframe): """ Get a dataframe from a complex mapped dataframe """ df = complex_dataframe mapper = DataFrameMapper( [('target', None), ('feat1', None), ('feat2', None)], df_out=True) transformed = mapper.fit_transform(df) assert len(transformed) == len(complex_dataframe) for c in df.columns: assert len(transformed[c]) == len(df[c]) def test_numeric_column_names(complex_dataframe): """ Get a dataframe from a complex mapped dataframe with numeric column names """ df = complex_dataframe df.columns = [0, 1, 2] mapper = DataFrameMapper( [(0, None), (1, None), (2, None)], df_out=True) transformed = mapper.fit_transform(df) assert len(transformed) == len(complex_dataframe) for c in df.columns: assert len(transformed[c]) == len(df[c]) def test_multiindex_df(multiindex_dataframe_incomplete): """ Get a dataframe from a multiindex dataframe with missing data """ df = multiindex_dataframe_incomplete mapper = DataFrameMapper([([c], Imputer()) for c in df.columns], df_out=True) transformed = mapper.fit_transform(df) assert len(transformed) == len(multiindex_dataframe_incomplete) for c in df.columns: assert len(transformed[str(c)]) == len(df[c]) def test_binarizer_df(): """ Check level names from LabelBinarizer """ df = pd.DataFrame({'target': ['a', 'a', 'b', 'b', 'c', 'a']}) mapper = DataFrameMapper([('target', LabelBinarizer())], df_out=True) transformed = mapper.fit_transform(df) cols = transformed.columns assert len(cols) == 3 assert cols[0] == 'target_a' assert cols[1] == 'target_b' assert cols[2] == 'target_c' def test_binarizer_int_df(): """ Check level names from LabelBinarizer for a numeric array. """ df = pd.DataFrame({'target': [5, 5, 6, 6, 7, 5]}) mapper = DataFrameMapper([('target', LabelBinarizer())], df_out=True) transformed = mapper.fit_transform(df) cols = transformed.columns assert len(cols) == 3 assert cols[0] == 'target_5' assert cols[1] == 'target_6' assert cols[2] == 'target_7' def test_binarizer2_df(): """ Check level names from LabelBinarizer with just one output column """ df = pd.DataFrame({'target': ['a', 'a', 'b', 'b', 'a']}) mapper = DataFrameMapper([('target', LabelBinarizer())], df_out=True) transformed = mapper.fit_transform(df) cols = transformed.columns assert len(cols) == 1 assert cols[0] == 'target' def test_onehot_df(): """ Check level ids from one-hot """ df = pd.DataFrame({'target': [0, 0, 1, 1, 2, 3, 0]}) mapper = DataFrameMapper([(['target'], OneHotEncoder())], df_out=True) transformed = mapper.fit_transform(df) cols = transformed.columns assert len(cols) == 4 assert cols[0] == 'target_x0_0' assert cols[3] == 'target_x0_3' def test_customtransform_df(): """ Check level ids from a transformer in which the number of classes is not equals to the number of output columns. """ df = pd.DataFrame({'target': [6, 5, 7, 5, 4, 8, 8]}) mapper = DataFrameMapper([(['target'], CustomTransformer())], df_out=True) transformed = mapper.fit_transform(df) cols = transformed.columns assert len(mapper.features[0][1].classes_) == 5 assert len(cols) == 1 assert cols[0] == 'target' def test_preserve_df_index(): """ The index is preserved when df_out=True """ df = pd.DataFrame({'target': [1, 2, 3]}, index=['a', 'b', 'c']) mapper = DataFrameMapper([('target', None)], df_out=True) transformed = mapper.fit_transform(df) assert_array_equal(transformed.index, df.index) def test_preserve_df_index_rows_dropped(): """ If df_out=True but the original df index length doesn't match the number of final rows, use a numeric index """ class DropLastRowTransformer(object): def fit(self, X): return self def transform(self, X): return X[:-1] df = pd.DataFrame({'target': [1, 2, 3]}, index=['a', 'b', 'c']) mapper = DataFrameMapper([('target', DropLastRowTransformer())], df_out=True) transformed = mapper.fit_transform(df) assert_array_equal(transformed.index, np.array([0, 1])) def test_pca(complex_dataframe): """ Check multi in and out with PCA """ df = complex_dataframe mapper = DataFrameMapper( [(['feat1', 'feat2'], sklearn.decomposition.PCA(2))], df_out=True) transformed = mapper.fit_transform(df) cols = transformed.columns assert len(cols) == 2 assert cols[0] == 'feat1_feat2_0' assert cols[1] == 'feat1_feat2_1' def test_fit_transform(simple_dataframe): """ Check that custom fit_transform methods of the transformers are invoked. """ df = simple_dataframe mock_transformer = Mock() # return something of measurable length but does nothing mock_transformer.fit_transform.return_value = np.array([1, 2, 3]) mapper = DataFrameMapper([("a", mock_transformer)]) mapper.fit_transform(df) assert mock_transformer.fit_transform.called def test_fit_transform_equiv_mock(simple_dataframe): """ Check for equivalent results for code paths fit_transform versus fit and transform in DataFrameMapper using the mock transformer which does not implement a custom fit_transform. """ df = simple_dataframe mapper = DataFrameMapper([('a', MockXTransformer())]) transformed_combined = mapper.fit_transform(df) transformed_separate = mapper.fit(df).transform(df) assert np.all(transformed_combined == transformed_separate) def test_fit_transform_equiv_pca(complex_dataframe): """ Check for equivalent results for code paths fit_transform versus fit and transform in DataFrameMapper and transformer using PCA which implements a custom fit_transform. The equivalence of both paths in the transformer only can be asserted since this is tested in the sklearn tests scikit-learn/sklearn/decomposition/tests/test_pca.py """ df = complex_dataframe mapper = DataFrameMapper( [(['feat1', 'feat2'], sklearn.decomposition.PCA(2))], df_out=True) transformed_combined = mapper.fit_transform(df) transformed_separate = mapper.fit(df).transform(df) assert np.allclose(transformed_combined, transformed_separate) def test_input_df_true_first_transformer(simple_dataframe, monkeypatch): """ If input_df is True, the first transformer is passed a pd.Series instead of an np.array """ df = simple_dataframe monkeypatch.setattr(MockXTransformer, 'fit', Mock()) monkeypatch.setattr(MockXTransformer, 'transform', Mock(return_value=np.array([1, 2, 3]))) mapper = DataFrameMapper([ ('a', MockXTransformer()) ], input_df=True) out = mapper.fit_transform(df) args, _ = MockXTransformer().fit.call_args assert isinstance(args[0], pd.Series) args, _ = MockXTransformer().transform.call_args assert isinstance(args[0], pd.Series) assert_array_equal(out, np.array([1, 2, 3]).reshape(-1, 1)) def test_input_df_true_next_transformers(simple_dataframe, monkeypatch): """ If input_df is True, the subsequent transformers get passed pandas objects instead of numpy arrays (given the previous transformers output pandas objects as well) """ df = simple_dataframe monkeypatch.setattr(MockTClassifier, 'fit', Mock()) monkeypatch.setattr(MockTClassifier, 'transform', Mock(return_value=pd.Series([1, 2, 3]))) mapper = DataFrameMapper([ ('a', [MockXTransformer(), MockTClassifier()]) ], input_df=True) mapper.fit(df) out = mapper.transform(df) args, _ = MockTClassifier().fit.call_args assert isinstance(args[0], pd.Series) assert_array_equal(out, np.array([1, 2, 3]).reshape(-1, 1)) def test_input_df_true_multiple_cols(complex_dataframe): """ When input_df is True, applying transformers to multiple columns works as expected """ df = complex_dataframe mapper = DataFrameMapper([ ('target', MockXTransformer()), ('feat1', MockXTransformer()), ], input_df=True) out = mapper.fit_transform(df) assert_array_equal(out[:, 0], df['target'].values) assert_array_equal(out[:, 1], df['feat1'].values) def test_input_df_date_encoder(): """ When input_df is True we can apply a transformer that only works with pandas dataframes like a DateEncoder """ df = pd.DataFrame( {'dates': pd.date_range('2015-10-30', '2015-11-02')}) mapper = DataFrameMapper([ ('dates', DateEncoder()) ], input_df=True) out = mapper.fit_transform(df) expected = np.array([ [2015, 10, 30], [2015, 10, 31], [2015, 11, 1], [2015, 11, 2] ]) assert_array_equal(out, expected) def test_local_input_df_date_encoder(): """ When input_df is True we can apply a transformer that only works with pandas dataframes like a DateEncoder """ df = pd.DataFrame( {'dates': pd.date_range('2015-10-30', '2015-11-02')}) mapper = DataFrameMapper([ ('dates', DateEncoder(), {'input_df': True}) ], input_df=False) out = mapper.fit_transform(df) expected = np.array([ [2015, 10, 30], [2015, 10, 31], [2015, 11, 1], [2015, 11, 2] ]) assert_array_equal(out, expected) def test_nonexistent_columns_explicit_fail(simple_dataframe): """ If a nonexistent column is selected, KeyError is raised. """ mapper = DataFrameMapper(None) with pytest.raises(KeyError): mapper._get_col_subset(simple_dataframe, ['nonexistent_feature']) def test_get_col_subset_single_column_array(simple_dataframe): """ Selecting a single column should return a 1-dimensional numpy array. """ mapper = DataFrameMapper(None) array = mapper._get_col_subset(simple_dataframe, "a") assert type(array) == np.ndarray assert array.shape == (len(simple_dataframe["a"]),) def test_get_col_subset_single_column_list(simple_dataframe): """ Selecting a list of columns (even if the list contains a single element) should return a 2-dimensional numpy array. """ mapper = DataFrameMapper(None) array = mapper._get_col_subset(simple_dataframe, ["a"]) assert type(array) == np.ndarray assert array.shape == (len(simple_dataframe["a"]), 1) def test_cols_string_array(simple_dataframe): """ If a string is specified as the columns, the transformer is called with a 1-d array as input. """ df = simple_dataframe mock_transformer = Mock() mapper = DataFrameMapper([("a", mock_transformer)]) mapper.fit(df) args, kwargs = mock_transformer.fit.call_args assert args[0].shape == (3,) def test_cols_list_column_vector(simple_dataframe): """ If a one-element list is specified as the columns, the transformer is called with a column vector as input. """ df = simple_dataframe mock_transformer = Mock() mapper = DataFrameMapper([(["a"], mock_transformer)]) mapper.fit(df) args, kwargs = mock_transformer.fit.call_args assert args[0].shape == (3, 1) def test_handle_feature_2dim(): """ 2-dimensional arrays are returned unchanged. """ array = np.array([[1, 2], [3, 4]]) assert_array_equal(_handle_feature(array), array) def test_handle_feature_1dim(): """ 1-dimensional arrays are converted to 2-dimensional column vectors. """ array = np.array([1, 2]) assert_array_equal(_handle_feature(array), np.array([[1], [2]])) def test_build_transformers(): """ When a list of transformers is passed, return a pipeline with each element of the iterable as a step of the pipeline. """ transformers = [MockTClassifier(), MockTClassifier()] pipeline = _build_transformer(transformers) assert isinstance(pipeline, Pipeline) for ix, transformer in enumerate(transformers): assert pipeline.steps[ix][1] == transformer def test_selected_columns(): """ selected_columns returns a set of the columns appearing in the features of the mapper. """ mapper = DataFrameMapper([ ('a', None), (['a', 'b'], None) ]) assert mapper._selected_columns == {'a', 'b'} def test_unselected_columns(): """ unselected_columns returns a list of the columns not appearing in the features of the mapper but present in the given dataframe. """ df = pd.DataFrame({'a': [1], 'b': [2], 'c': [3]}) mapper = DataFrameMapper([ ('a', None), (['a', 'b'], None) ]) assert 'c' in mapper._unselected_columns(df) def test_drop_and_default_false(): """ If default=False, non explicitly selected columns and drop columns are discarded. """ df = pd.DataFrame({'a': [1], 'b': [2], 'c': [3]}) mapper = DataFrameMapper([ ('a', None) ], drop_cols=['c'], default=False) transformed = mapper.fit_transform(df) assert transformed.shape == (1, 1) assert mapper.transformed_names_ == ['a'] def test_drop_and_default_none(): """ If default=None, drop columns are discarded and remaining non explicitly selected columns are passed through untransformed """ df = pd.DataFrame({'a': [1, 2, 3], 'b': [3, 5, 7]}) mapper = DataFrameMapper([ ('a', None) ], drop_cols=['c'], default=None) transformed = mapper.fit_transform(df) assert transformed.shape == (3, 2) assert mapper.transformed_names_ == ['a', 'b'] def test_conflicting_drop(): """ Drop column name shouldn't get confused with transformed columns. """ df = pd.DataFrame({'a': [1, 2, 3], 'b': [3, 5, 7]}) mapper = DataFrameMapper([ ('a', None) ], drop_cols=['a'], default=False) transformed = mapper.fit_transform(df) assert transformed.shape == (3, 1) assert mapper.transformed_names_ == ['a'] def test_default_false(): """ If default=False, non explicitly selected columns are discarded. """ df = pd.DataFrame({'a': [1, 2, 3], 'b': [3, 5, 7]}) mapper = DataFrameMapper([ ('b', None) ], default=False) transformed = mapper.fit_transform(df) assert transformed.shape == (3, 1) def test_default_none(): """ If default=None, non explicitly selected columns are passed through untransformed. """ df = pd.DataFrame({'a': [1, 2, 3], 'b': [3, 5, 7]}) mapper = DataFrameMapper([ (['a'], OneHotEncoder()) ], default=None) transformed = mapper.fit_transform(df) assert (transformed[:, 3] == np.array([3, 5, 7]).T).all() def test_default_none_names(): """ If default=None, column names are returned unmodified. """ df = pd.DataFrame({'a': [1, 2, 3], 'b': [3, 5, 7]}) mapper = DataFrameMapper([], default=None) mapper.fit_transform(df) assert mapper.transformed_names_ == ['a', 'b'] def test_default_transformer(): """ If default=Transformer, non explicitly selected columns are applied this transformer. """ df = pd.DataFrame({'a': [1, np.nan, 3], }) mapper = DataFrameMapper([], default=Imputer()) transformed = mapper.fit_transform(df) assert (transformed[: 0] == np.array([1., 2., 3.])).all() def test_list_transformers_single_arg(simple_dataframe): """ Multiple transformers can be specified in a list even if some of them only accept one X argument instead of two (X, y). """ mapper = DataFrameMapper([ ('a', [MockXTransformer()]) ]) # doesn't fail mapper.fit_transform(simple_dataframe) def test_list_transformers(): """ Specifying a list of transformers applies them sequentially to the selected column. """ dataframe = pd.DataFrame({"a": [1, np.nan, 3], "b": [1, 5, 7]}, dtype=np.float64) mapper = DataFrameMapper([ (["a"], [Imputer(), StandardScaler()]), (["b"], StandardScaler()), ]) dmatrix = mapper.fit_transform(dataframe) assert pd.isnull(dmatrix).sum() == 0 # no null values # all features have mean 0 and std deviation 1 (standardized) assert (abs(dmatrix.mean(axis=0) - 0) <= 1e-6).all() assert (abs(dmatrix.std(axis=0) - 1) <= 1e-6).all() def test_list_transformers_old_unpickle(simple_dataframe): mapper = DataFrameMapper(None) # simulate the mapper was created with < 1.0.0 code mapper.features = [('a', [MockXTransformer()])] mapper_pickled = pickle.dumps(mapper) loaded_mapper = pickle.loads(mapper_pickled) transformer = loaded_mapper.features[0][1] assert isinstance(transformer, TransformerPipeline) assert isinstance(transformer.steps[0][1], MockXTransformer) def test_sparse_features(simple_dataframe): """ If any of the extracted features is sparse and "sparse" argument is true, the hstacked result is also sparse. """ df = simple_dataframe mapper = DataFrameMapper([ ("a", ToSparseTransformer()) ], sparse=True) dmatrix = mapper.fit_transform(df) assert type(dmatrix) == sparse.csr.csr_matrix def test_sparse_off(simple_dataframe): """ If the resulting features are sparse but the "sparse" argument of the mapper is False, return a non-sparse matrix. """ df = simple_dataframe mapper = DataFrameMapper([ ("a", ToSparseTransformer()) ], sparse=False) dmatrix = mapper.fit_transform(df) assert type(dmatrix) != sparse.csr.csr_matrix def test_fit_with_optional_y_arg(complex_dataframe): """ Transformers with an optional y argument in the fit method are handled correctly """ df = complex_dataframe mapper = DataFrameMapper([(['feat1', 'feat2'], MockTClassifier())]) # doesn't fail mapper.fit(df[['feat1', 'feat2']], df['target']) def test_fit_with_required_y_arg(complex_dataframe): """ Transformers with a required y argument in the fit method are handled and perform correctly """ df = complex_dataframe mapper = DataFrameMapper([(['feat1', 'feat2'], SelectKBest(chi2, k=1))]) # fit, doesn't fail ft_arr = mapper.fit(df[['feat1', 'feat2']], df['target']) # fit_transform ft_arr = mapper.fit_transform(df[['feat1', 'feat2']], df['target']) assert_array_equal(ft_arr, df[['feat1']].values) # transform t_arr = mapper.transform(df[['feat1', 'feat2']]) assert_array_equal(t_arr, df[['feat1']].values) # Integration tests with real dataframes @pytest.fixture def iris_dataframe(): iris = load_iris() return DataFrame( data={ iris.feature_names[0]: iris.data[:, 0], iris.feature_names[1]: iris.data[:, 1], iris.feature_names[2]: iris.data[:, 2], iris.feature_names[3]: iris.data[:, 3], "species": np.array([iris.target_names[e] for e in iris.target]) } ) @pytest.fixture def cars_dataframe(): return pd.read_csv("tests/test_data/cars.csv.gz", compression='gzip') def test_with_iris_dataframe(iris_dataframe): pipeline = Pipeline([ ("preprocess", DataFrameMapper([ ("petal length (cm)", None), ("petal width (cm)", None), ("sepal length (cm)", None), ("sepal width (cm)", None), ])), ("classify", SVC(kernel='linear')) ]) data = iris_dataframe.drop("species", axis=1) labels = iris_dataframe["species"] scores = cross_val_score(pipeline, data, labels) assert scores.mean() > 0.96 assert (scores.std() * 2) < 0.04 def test_dict_vectorizer(): df = pd.DataFrame( [[{'a': 1, 'b': 2}], [{'a': 3}]], columns=['colA'] ) outdf = DataFrameMapper( [('colA', DictVectorizer())], df_out=True, default=False ).fit_transform(df) columns = sorted(list(outdf.columns)) assert len(columns) == 2 assert columns[0] == 'colA_a' assert columns[1] == 'colA_b' def test_with_car_dataframe(cars_dataframe): pipeline = Pipeline([ ("preprocess", DataFrameMapper([ ("description", CountVectorizer()), ])), ("classify", SVC(kernel='linear')) ]) data = cars_dataframe.drop("model", axis=1) labels = cars_dataframe["model"] scores = cross_val_score(pipeline, data, labels) assert scores.mean() > 0.30 def test_direct_cross_validation(iris_dataframe): """ Starting with sklearn>=0.16.0 we no longer need CV wrappers for dataframes. See https://github.com/paulgb/sklearn-pandas/issues/11 """ pipeline = Pipeline([ ("preprocess", DataFrameMapper([ ("petal length (cm)", None), ("petal width (cm)", None), ("sepal length (cm)", None), ("sepal width (cm)", None), ])), ("classify", SVC(kernel='linear')) ]) data = iris_dataframe.drop("species", axis=1) labels = iris_dataframe["species"] scores = cross_val_score(pipeline, data, labels) assert scores.mean() > 0.96 assert (scores.std() * 2) < 0.04 def test_heterogeneous_output_types_input_df(): """ Modify feat2, but pass feat1 through unmodified. This fails if input_df == False """ df = pd.DataFrame({ 'feat1': [1, 2, 3, 4, 5, 6], 'feat2': [1.0, 2.0, 3.0, 2.0, 3.0, 4.0] }) M = DataFrameMapper([ (['feat2'], StandardScaler()) ], input_df=True, df_out=True, default=None) dft = M.fit_transform(df) assert dft['feat1'].dtype == np.dtype('int64') assert dft['feat2'].dtype == np.dtype('float64') def test_make_column_selector(iris_dataframe): t = DataFrameMapper([ (make_column_selector(dtype_include=float), None, {'alias': 'x'}), ('sepal length (cm)', None), ], df_out=True, default=False) xt = t.fit(iris_dataframe).transform(iris_dataframe) expected = ['x_0', 'x_1', 'x_2', 'x_3', 'sepal length (cm)'] assert list(xt.columns) == expected pickled = pickle.dumps(t) t2 = pickle.loads(pickled) xt2 = t2.transform(iris_dataframe) assert np.array_equal(xt.values, xt2.values) sklearn-pandas-2.2.0/tests/test_features_generator.py000066400000000000000000000063701421000130300230430ustar00rootroot00000000000000from collections import Counter import pytest import numpy as np from pandas import DataFrame from numpy.testing import assert_array_equal from sklearn_pandas import DataFrameMapper from sklearn_pandas.features_generator import gen_features class MockClass(object): def __init__(self, value=1, name='class'): self.value = value self.name = name class MockTransformer(object): def __init__(self): self.most_common_ = None def fit(self, X, y=None): [(value, _)] = Counter(X).most_common(1) self.most_common_ = value return self def transform(self, X, y=None): return np.asarray([self.most_common_] * len(X)) @pytest.fixture def simple_dataset(): return DataFrame({ 'feat1': [1, 2, 1, 3, 1], 'feat2': [1, 2, 2, 2, 3], 'feat3': [1, 2, 3, 4, 5], }) def test_generate_features_with_default_parameters(): """ Tests generating features from classes with default init arguments. """ columns = ['colA', 'colB', 'colC'] feature_defs = gen_features(columns=columns, classes=[MockClass]) assert len(feature_defs) == len(columns) for feature in feature_defs: assert feature[2] == {} feature_dict = dict([_[0:2] for _ in feature_defs]) assert columns == sorted(feature_dict.keys()) # default init arguments for MockClass for clarification. expected = {'value': 1, 'name': 'class'} for column, transformers in feature_dict.items(): for obj in transformers: assert_attributes(obj, **expected) def test_generate_features_with_several_classes(): """ Tests generating features pipeline with different transformers parameters. """ feature_defs = gen_features( columns=['colA', 'colB', 'colC'], classes=[ {'class': MockClass}, {'class': MockClass, 'name': 'mockA'}, {'class': MockClass, 'name': 'mockB', 'value': None} ] ) for col, transformers, params in feature_defs: assert_attributes(transformers[0], name='class', value=1) assert_attributes(transformers[1], name='mockA', value=1) assert_attributes(transformers[2], name='mockB', value=None) def test_generate_features_with_none_only_transformers(): """ Tests generating "dummy" feature definition which doesn't apply any transformation. """ feature_defs = gen_features( columns=['colA', 'colB', 'colC'], classes=[None]) expected = [('colA', None, {}), ('colB', None, {}), ('colC', None, {})] assert feature_defs == expected def test_compatibility_with_data_frame_mapper(simple_dataset): """ Tests compatibility of generated feature definition with DataFrameMapper. """ features_defs = gen_features( columns=['feat1', 'feat2'], classes=[MockTransformer]) features_defs.append(('feat3', None)) mapper = DataFrameMapper(features_defs) X = mapper.fit_transform(simple_dataset) expected = np.asarray([ [1, 2, 1], [1, 2, 2], [1, 2, 3], [1, 2, 4], [1, 2, 5] ]) assert_array_equal(X, expected) def assert_attributes(obj, **attrs): for attr, value in attrs.items(): assert getattr(obj, attr) == value sklearn-pandas-2.2.0/tests/test_pipeline.py000066400000000000000000000046071421000130300207650ustar00rootroot00000000000000import pytest from sklearn_pandas.pipeline import TransformerPipeline, _call_fit # In py3, mock is included with the unittest standard library # In py2, it's a separate package try: from unittest.mock import patch except ImportError: from mock import patch class NoTransformT(object): """Transformer without transform method. """ def fit(self, x): return self class NoFitT(object): """Transformer without fit method. """ def transform(self, x): return self class Trans(object): """ Transformer with fit and transform methods """ def fit(self, x, y=None): return self def transform(self, x): return self def func_x_y(x, y, kwarg='kwarg'): """ Function with required x and y arguments """ return def func_x(x, kwarg='kwarg'): """ Function with required x argument """ return def func_raise_type_err(x, y, kwarg='kwarg'): """ Function with required x and y arguments, raises TypeError """ raise TypeError def test_all_steps_fit_transform(): """ All steps must implement fit and transform. Otherwise, raise TypeError. """ with pytest.raises(TypeError): TransformerPipeline([('svc', NoTransformT())]) with pytest.raises(TypeError): TransformerPipeline([('svc', NoFitT())]) @patch.object(Trans, 'fit', side_effect=func_x_y) def test_called_with_x_and_y(mock_fit): """ Fit method with required X and y arguments is called with both and with any additional keywords """ _call_fit(Trans().fit, 'X', 'y', kwarg='kwarg') mock_fit.assert_called_with('X', 'y', kwarg='kwarg') @patch.object(Trans, 'fit', side_effect=func_x) def test_called_with_x(mock_fit): """ Fit method with a required X arguments is called with it and with any additional keywords """ _call_fit(Trans().fit, 'X', 'y', kwarg='kwarg') mock_fit.assert_called_with('X', kwarg='kwarg') _call_fit(Trans().fit, 'X', kwarg='kwarg') mock_fit.assert_called_with('X', kwarg='kwarg') @patch.object(Trans, 'fit', side_effect=func_raise_type_err) def test_raises_type_error(mock_fit): """ If a fit method with required X and y arguments raises a TypeError, it's re-raised (for a different reason) when it's called with one argument """ with pytest.raises(TypeError): _call_fit(Trans().fit, 'X', 'y', kwarg='kwarg') sklearn-pandas-2.2.0/tests/test_transformers.py000066400000000000000000000023001421000130300216710ustar00rootroot00000000000000import tempfile import pytest import numpy as np from pandas import DataFrame import joblib from sklearn_pandas import DataFrameMapper from sklearn_pandas import NumericalTransformer @pytest.fixture def simple_dataset(): return DataFrame({ 'feat1': [1, 2, 1, 3, 1], 'feat2': [1, 2, 2, 2, 3], 'feat3': [1, 2, 3, 4, 5], }) def test_common_numerical_transformer(simple_dataset): """ Test log transformation """ transfomer = DataFrameMapper([ ('feat1', NumericalTransformer('log')) ], df_out=True) df = simple_dataset outDF = transfomer.fit_transform(df) assert list(outDF.columns) == ['feat1'] assert np.array_equal(df['feat1'].apply(np.log).values, outDF.feat1.values) def test_numerical_transformer_serialization(simple_dataset): """ Test if you can serialize transformer """ transfomer = DataFrameMapper([ ('feat1', NumericalTransformer('log')) ]) df = simple_dataset transfomer.fit(df) f = tempfile.NamedTemporaryFile(delete=True) joblib.dump(transfomer, f.name) transfomer2 = joblib.load(f.name) np.array_equal(transfomer.transform(df), transfomer2.transform(df)) f.close()