python 如何自动检测列是否为分类列?

myzjeezk  于 2022-11-27  发布在  Python
关注(0)|答案(2)|浏览(231)

我想找一个Pandas专栏的分类。我可以找到类型,但我很难找出分类。

titanic_df = pd.read_csv('http://biostat.mc.vanderbilt.edu/wiki/pub/Main/DataSets/titanic3.csv')

#ID datatype

def idDataTypes(inputDataFrame):
    columnTypesDict = {} 
    import numpy as np
    import numbers
    import pandas as pd
    from pandas.api.types import is_string_dtype
    from pandas.api.types import is_numeric_dtype

    for columns in inputDataFrame.columns.values:
        #print(columns)
        #try to convert to number. If it doesn't work it will convert to another type
        try:
            inputDataFrame[columns] = pd.to_numeric(inputDataFrame[columns], errors='ignore').apply(lambda x: x + 1 if isinstance(x, numbers.Number) else x) 
        except:
            print(columns, " cannot convert.")
        #print(inputDataFrame[columns].dtype)

        #create dictionary with the label
        if is_numeric_dtype(inputDataFrame[columns]): #products[columns].dtype == np.float64:
            columnTypesDict[columns] = "numeric"
        elif is_string_dtype(inputDataFrame[columns]): # products[columns].dtype == np.object:
            columnTypesDict[columns] = "string"
            #print(is_string_dtype(products[columns]))
        else:
            print("something else", prinputDataFrameoducts[columns].dtype)

    #category 
    cols = inputDataFrame.columns
    num_cols = inputDataFrame._get_numeric_data().columns
    #num_cols
    proposedCategory = list(set(cols) - set(num_cols))
    for value in proposedCategory:
        columnTypesDict[value] = "category"

    return(columnTypesDict)

idDataTypes(titanic_df)

我得到的结果不是我所期望的:

{'pclass': 'numeric',
 'survived': 'numeric',
 'name': 'category',
 'sex': 'category',
 'age': 'numeric',
 'sibsp': 'numeric',
 'parch': 'numeric',
 'ticket': 'category',
 'fare': 'numeric',
 'cabin': 'category',
 'embarked': 'category',
 'boat': 'category',
 'body': 'numeric',
 'home.dest': 'category'}

pclass应该是类别,而name不应该是。
我不知道如何评估某个东西是否是一个类别。有什么想法吗?

cedebl8k

cedebl8k1#

下面是代码中的错误:

proposedCategory = list(set(cols) - set(num_cols))

除数值列之外的所有内容都将成为类别。
也没有正确的方法来执行此操作,因为最好根据列所包含数据的知识手动确定列是否为分类列。您尝试自动执行此操作。一种方法是计算列中唯一值的数量。如果唯一值相对较少,则该列很可能为分类列。

#category 
for name, column in inputDataFrame.iteritems():
    unique_count = column.unique().shape[0]
    total_count = column.shape[0]
    if unique_count / total_count < 0.05:
        columnTypesDict[name] = 'category'

5%阈值是随机的。如果 Dataframe 中的行少于20,则不会将任何列标识为分类列。要获得最佳结果,必须调整大小 Dataframe 的比率。

2g32fytz

2g32fytz2#

快一点我发现的解决方法是使用Pandas。corr()方法来自动将数值列斜线化。根据我的观察,.corr()在返回整个 Dataframe 的成对相关性时自动选择数值列。(前提是你已经在整个数据集上应用了它)。因此你总是可以在你的原始 Dataframe 中线性搜索分类列,如果它不在.corr()返回的 Dataframe 中。这可能不是100%有效,但它在大部分时间都能完成任务。

corr_df = df.corr() #returns a dataframe
num_cols = corr_df.columns
cat_cols = [cols for cols in df.columns if not cols in num_cols]

PS:如果数据集包含很多列,可能会占用一些时间/内存。

相关问题