【问题标题】:LabelEncoder within Lambda functionLambda 函数中的 LabelEncoder
【发布时间】:2018-12-28 06:23:00
【问题描述】:

我正在处理爱荷华州 Ames 的住房数据,我想在 lambda 函数中使用 LabelEncoder 来标记我的分类特征中的字符串值,同时跳过 NaN 值(这样我就可以估算它们之后)。这是我目前所拥有的:

train['Fireplace Qu'].apply(lambda x: LabelEncoder(x).fit_transform if type(x) != np.float else x)

但它会抛出这个错误:

TypeError: object() takes no parameters

任何帮助将不胜感激 - 试图找出一种估算分类数据的方法。

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    让我们使用factorize

    pd.Series(pd.factorize(df.group)[0]).replace(-1,np.nan)
    Out[141]: 
    0    NaN
    1    NaN
    2    0.0
    3    0.0
    4    NaN
    5    NaN
    6    NaN
    7    NaN
    8    1.0
    dtype: float64
    

    或者

    df.loc[df.group.notnull(),'group']=df.group.astype('category').cat.codes
    

    数据输入

      group
    0   NaN
    1   NaN
    2     a
    3     a
    4   NaN
    5   NaN
    6   NaN
    7   NaN
    8     b
    

    【讨论】:

      猜你喜欢
      • 2019-02-25
      • 2020-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-06
      • 2017-04-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多