pax_global_header00006660000000000000000000000064137601742320014517gustar00rootroot0000000000000052 comment=efb6dd55c6f4c328f84b3128d60628838fc46dd2 sklearn-pandas-2.0.3/000077500000000000000000000000001376017423200144245ustar00rootroot00000000000000sklearn-pandas-2.0.3/LICENSE000066400000000000000000000045461376017423200154420ustar00rootroot00000000000000sklearn-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.0.3/MANIFEST.in000066400000000000000000000000431376017423200161570ustar00rootroot00000000000000include LICENSE include README.rst sklearn-pandas-2.0.3/PKG-INFO000066400000000000000000000004751376017423200155270ustar00rootroot00000000000000Metadata-Version: 1.2 Name: sklearn-pandas Version: 2.0.3 Summary: Pandas integration with sklearn Home-page: https://github.com/scikit-learn-contrib/sklearn-pandas Maintainer: Ritesh Agrawal Maintainer-email: ragrawal@gmail.com License: UNKNOWN Description: UNKNOWN Keywords: scikit,sklearn,pandas Platform: UNKNOWN sklearn-pandas-2.0.3/README.rst000066400000000000000000000545761376017423200161340ustar00rootroot00000000000000 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 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 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 >>> 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. The first element of each tuple 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). The second element is an object which will perform the transformation which will be applied to that column. 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'] 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.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 * 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.0.3/setup.cfg000066400000000000000000000000751376017423200162470ustar00rootroot00000000000000[wheel] universal = 1 [egg_info] tag_build = tag_date = 0 sklearn-pandas-2.0.3/setup.py000066400000000000000000000024671376017423200161470ustar00rootroot00000000000000#!/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.4.1', 'pandas>=1.0.5', 'numpy>=1.18.1' ], tests_require=['pytest', 'mock'], cmdclass={'test': PyTest}, ) sklearn-pandas-2.0.3/sklearn_pandas.egg-info/000077500000000000000000000000001376017423200211035ustar00rootroot00000000000000sklearn-pandas-2.0.3/sklearn_pandas.egg-info/PKG-INFO000066400000000000000000000004751376017423200222060ustar00rootroot00000000000000Metadata-Version: 1.2 Name: sklearn-pandas Version: 2.0.3 Summary: Pandas integration with sklearn Home-page: https://github.com/scikit-learn-contrib/sklearn-pandas Maintainer: Ritesh Agrawal Maintainer-email: ragrawal@gmail.com License: UNKNOWN Description: UNKNOWN Keywords: scikit,sklearn,pandas Platform: UNKNOWN sklearn-pandas-2.0.3/sklearn_pandas.egg-info/SOURCES.txt000066400000000000000000000006561376017423200227760ustar00rootroot00000000000000LICENSE MANIFEST.in README.rst setup.cfg setup.py sklearn_pandas/__init__.py sklearn_pandas/cross_validation.py sklearn_pandas/dataframe_mapper.py sklearn_pandas/features_generator.py sklearn_pandas/pipeline.py sklearn_pandas/transformers.py sklearn_pandas.egg-info/PKG-INFO sklearn_pandas.egg-info/SOURCES.txt sklearn_pandas.egg-info/dependency_links.txt sklearn_pandas.egg-info/requires.txt sklearn_pandas.egg-info/top_level.txtsklearn-pandas-2.0.3/sklearn_pandas.egg-info/dependency_links.txt000066400000000000000000000000011376017423200251510ustar00rootroot00000000000000 sklearn-pandas-2.0.3/sklearn_pandas.egg-info/requires.txt000066400000000000000000000000761376017423200235060ustar00rootroot00000000000000scikit-learn>=0.23.0 scipy>=1.4.1 pandas>=1.0.5 numpy>=1.18.1 sklearn-pandas-2.0.3/sklearn_pandas.egg-info/top_level.txt000066400000000000000000000000171376017423200236330ustar00rootroot00000000000000sklearn_pandas sklearn-pandas-2.0.3/sklearn_pandas/000077500000000000000000000000001376017423200174115ustar00rootroot00000000000000sklearn-pandas-2.0.3/sklearn_pandas/__init__.py000066400000000000000000000003551376017423200215250ustar00rootroot00000000000000__version__ = '2.0.3' 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.0.3/sklearn_pandas/cross_validation.py000066400000000000000000000003031376017423200233220ustar00rootroot00000000000000class 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.0.3/sklearn_pandas/dataframe_mapper.py000066400000000000000000000362151376017423200232620ustar00rootroot00000000000000import 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={}): return (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): """ Build attributes built_features and built_default. """ if isinstance(self.features, list): self.built_features = [_build_feature(*f) for f in self.features] else: self.built_features = self.features 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 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 _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 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() 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() extracted = [] self.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', '') self.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) self.transformed_names_ += self.get_names( unsel_cols, self.built_default, Xt) else: # if not applying a default transformer, # keep column names unmodified self.transformed_names_ += unsel_cols extracted.append(_handle_feature(Xt)) # 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.0.3/sklearn_pandas/features_generator.py000066400000000000000000000042071376017423200236520ustar00rootroot00000000000000def 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.0.3/sklearn_pandas/pipeline.py000066400000000000000000000067621376017423200216030ustar00rootroot00000000000000import 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.0.3/sklearn_pandas/transformers.py000066400000000000000000000025061376017423200225130ustar00rootroot00000000000000import numpy as np import pandas as pd from sklearn.base import TransformerMixin 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. """ 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}")