【问题标题】:How can do improve this code for use OneHotEncoder? [duplicate]如何改进此代码以使用 OneHotEncoder? [复制]
【发布时间】:2020-03-16 14:42:11
【问题描述】:

您好,我正在使用以下函数将数据集中的所有分类值转换为数值,但我想将其转换为使用 OneHotEncoder,请问怎么做?

def categorical_to_numerical(dataframe):
    for col in dataframe.columns:
        if str(dataframe[col].dtype) == 'category':
            dataframe[col] = dataframe[col].astype("category").cat.codes
    return dataframe

谢谢

【问题讨论】:

    标签: python pandas scikit-learn


    【解决方案1】:

    如果我理解正确,您想使用DataFrame.select_dtypes 来选择object (string) 列。

    # example dataframe
    df = pd.DataFrame({'col1':[1,2,3],
                       'col2':['a','b','a'],
                       'col3':[4,5,6],
                       'col4':['aaa', 'bbb', 'bbb']})
    
       col1 col2  col3 col4
    0     1    a     4  aaa
    1     2    b     5  bbb
    2     3    a     6  bbb
    
    for col in df.select_dtypes('object'):
        df[col] = df[col].astype('category').cat.codes
    
       col1  col2  col3  col4
    0     1     0     4     0
    1     2     1     5     1
    2     3     0     6     1
    

    或者如果你真的想OneHotEncode,我们可以使用pd.get_dummies

    df = pd.get_dummies(df)
    
       col1  col3  col2_a  col2_b  col4_aaa  col4_bbb
    0     1     4       1       0         1         0
    1     2     5       0       1         0         1
    2     3     6       1       0         0         1
    

    【讨论】:

    • 我想用 OneHotEncoder 替换 cat.codes
    • 如果您想要第二种解决方案,请告诉我,那么它是重复的
    • 第二个选项是anwser谢谢
    猜你喜欢
    • 2016-12-20
    • 1970-01-01
    • 1970-01-01
    • 2018-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多