【问题标题】:One hot encoding a column with 28 different countires with only 6 classes一个热编码一列有 28 个不同的国家,只有 6 个类
【发布时间】:2020-04-11 22:24:24
【问题描述】:

我有一个数据集,其中“国家”列有 28 个不同的国家。我需要首先对列进行“标签编码”,然后仅使用 6 个标签对其进行“一个热编码”:前 5 个最常见的国家:美国、中国、日本、法国、加拿大和第 6 个标签是“其他”的任何其他国家专栏

【问题讨论】:

    标签: python pandas data-science


    【解决方案1】:

    你可以使用np.where:

    countries = ['USA', 'CHINA', 'JAPAN', 'FRANCE', 'CANADA']
    df['country_cat'] = np.where(df['country'].isin(countries), 
                                 df['country'], 'OTHER')
    
    # and then you can use `pd.get_dummies`
    pd.get_dummies(df['country_cat'])
    

    【讨论】:

      【解决方案2】:

      您可以使用lambda 尝试这个简单的解决方案。 lambda 中的 if elif else 条件甚至可以帮助您进一步分类!

      top = ['USA', 'CHINA', 'JAPAN', 'FRANCE', 'CANADA']
      df['country'] = df['country'].apply(lambda x : 'OTHERS' if x not in top else x)
      pd.get_dummies(df['country'])
      

      【讨论】:

      • 是否也可以使用一个可以从 sklearn 导入的热编码程序来完成?
      猜你喜欢
      • 2023-02-23
      • 1970-01-01
      • 2018-07-17
      • 2023-03-18
      • 2011-03-14
      • 1970-01-01
      • 2020-09-12
      • 2021-09-26
      • 2021-01-04
      相关资源
      最近更新 更多