首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >熊猫同时转换多个列的错误

熊猫同时转换多个列的错误
EN

Stack Overflow用户
提问于 2017-11-07 13:40:15
回答 1查看 1.1K关注 0票数 0

我在pandassklearn中使用python,并尝试使用新的非常方便的sklearn-pandas

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

在变量other中有多个列名--源代码文档这里声明--可以使用相同的转换显式地转换多个列,但以下代码的行为不像预期的那样:

代码语言:javascript
复制
from sklearn.preprocessing import MinMaxScaler, LabelEncoder

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

我得到以下错误:

提高ValueError(“坏输入形状{0}".format( shape )) ValueError:'EFW','BPD':坏输入形状(154,2)

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

代码语言:javascript
复制
cols = [(other[i], LabelEncoder()) for i,col in enumerate(other)]
mapper = DataFrameMapper(cols)
mapper.fit_transform(df.copy())

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

谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-11-07 14:19:35

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

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

代码语言:javascript
复制
cols = [(col, LabelEncoder()) for col in other]

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

转换可能需要多个输入列。在这些情况下,列名可以在列表中指定: mapper2 = DataFrameMapper([ (‘子女’,‘工资’,sklearn.decomposition.PCA(1) ])

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

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

代码语言:javascript
复制
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'}

类定义中还清楚地指出,DataFrameMapper的特性参数必须是元组的列表,其中元组的元素可以是列表。

作为最后一个注意事项,关于为什么您实际上得到了错误消息:sklearn中的sklearn转换器是用来在一维数组上标记的。因此,它根本无法同时处理2列,并将引发异常。因此,如果您想使用LabelEncoder,您必须构建N个元组,其中包含一个列名和转换器,其中N是您希望转换的列的数量。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47159415

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档