【问题标题】:How to identify the categorical variables in the 200+ numerical variables?如何识别200+数值变量中的分类变量?
【发布时间】:2018-04-16 02:54:15
【问题描述】:

我有一个包含 200 多个数值变量(类型:int)的数据集。在这些变量中,有一些是具有 (0,1)、(0,1,2,3,4) 等值的分类变量。

我需要识别这些分类变量并将它们虚拟化。 识别和虚拟化它们需要大量时间 - 有什么方法可以轻松完成?

【问题讨论】:

标签: python-3.x machine-learning data-science data-cleaning


【解决方案1】:

您可以说某些变量是分类变量,或者通过其唯一值的长度将它们视为分类变量。例如,如果一个变量只有唯一值 [-2,4,56],您可以将此变量视为分类变量。

import pandas as pd
import numpy as np
col = [c for c in train.columns if c not in ['id','target']]
numclasses=[]
for c in col:
    numclasses.append(len(np.unique(train[[c]])))

threshold=10
categorical_variables = list(np.array(col2)[np.array(numclasses2)<threshold]

每个被视为分类的变量中的每个唯一值都将创建一个新列。如果您不想稍后创建太多列作为虚拟对象,则可以使用小阈值。

【讨论】:

    【解决方案2】:

    使用nunique() 函数获取每列中唯一值的数量,然后过滤列。使用您的最佳判断来初始化threshold 值。将特征转换为分类类型

    category_features = []
    threshold = 10
    for each in df.columns:
        if df[each].nunique() < threshold:
            category_features.append(each)
    
    for each in category_features:
        df[each] = df[each].astype('category')
    

    【讨论】:

      【解决方案3】:

      What is a good heuristic to detect if a column in a pandas.DataFrame is categorical? 可能重复

      这篇文章有更多的答案。其中任何一个都可能对您有所帮助。看看吧

      【讨论】:

        猜你喜欢
        • 2016-08-25
        • 1970-01-01
        • 1970-01-01
        • 2019-04-24
        • 1970-01-01
        • 1970-01-01
        • 2015-10-23
        • 1970-01-01
        • 2015-12-14
        相关资源
        最近更新 更多