Python sklearn-pandas Transform Multiple Columns at the time error

Python sklearn-pandas Transform Multiple Columns at the same time error

我将 python 与 pandassklearn 一起使用,并尝试使用新的且非常方便的 sklearn-pandas

我有一个大数据框,需要以类似的方式转换多个列。

我在变量中有多个列名 other 源代码文档 here 明确指出可以使用相同的转换来转换多个列,但以下代码的行为与预期不符:

from sklearn.preprocessing import MinMaxScaler, LabelEncoder

mapper = DataFrameMapper([[other[0],other[1]],LabelEncoder()])
mapper.fit_transform(df.copy())

我收到以下错误:

raise ValueError("bad input shape {0}".format(shape)) ValueError: ['EFW', 'BPD']: bad input shape (154, 2)

当我使用以下代码时,效果很好:

cols = [(other[i], LabelEncoder()) for i,col in enumerate(other)]
mapper = DataFrameMapper(cols)
mapper.fit_transform(df.copy())

据我了解,两者都应该运作良好并产生相同的结果。 我在这里做错了什么?

谢谢!

你在这里遇到的问题是,这两段代码在数据结构上完全不同。

cols = [(other[i], LabelEncoder()) for i,col in enumerate(other)] 构建一个元组列表。请注意,您可以将这行代码缩短为:

cols = [(col, LabelEncoder()) for col in other]

无论如何,第一个片段 [[other[0],other[1]],LabelEncoder()] 生成一个包含两个元素的列表:一个列表和一个 LabelEncoder 实例。现在,记录了您可以通过指定转换多列:

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)) ])

这是一个 list 包含 tuple(list, object) 个结构化元素,而不是 list[list, object] 个结构化元素。

如果我们看一下源代码本身,

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):
        """
        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'}

在class定义中也明确指出DataFrameMapper的features参数要求是一个元组列表,其中元组的元素可以是列表。

最后一点,关于您实际收到错误消息的原因:sklearn 中的 LabelEncoder 转换器用于在一维数组上进行标记。因此,它根本无法同时处理 2 列,并且会引发异常。所以,如果你想使用 LabelEncoder,你将不得不用 1 个列名和转换器构建 N 个元组,其中 N 是你希望转换的列的数量。