【问题标题】:Hotencoded values & DataFrame for logistic regression热编码值到 DataFrame 以进行逻辑回归
【发布时间】:2020-09-25 20:05:26
【问题描述】:

我正在尝试对具有某些分类值的特征的数据集运行逻辑回归。为了通过回归处理这些特征,我打算对它们进行编码

#Select categorical features only & encode name numerically with LabelEncoder
cat_features = df.select_dtypes(include=[object])

label_enc = preprocessing.LabelEncoder()
le_features = cat_features.apply(label_enc.fit_transform)

#Aggregate all encoded values into a binary matrix
enc = preprocessing.OneHotEncoder()
enc.fit(le_features)
final_cat_features = enc.transform(le_features).toarray()

运行此代码后,我确实确认它返回了一个编码矩阵

(4665, 290)
<class 'numpy.ndarray'>

这就是我卡住的地方。我应该如何准确地从中重新生成数据框?!我是否应该将 290 列连接在一起,以便最终将新功能添加到我的新数据框中?如果没有,我不得不说我被困在这里了。

【问题讨论】:

    标签: python pandas dataframe encoding scikit-learn


    【解决方案1】:

    您应该将所有 290 列与剩余(即非分类或数字)值一起添加到数据框中。为此,您可以从数组创建一个数据框并将其连接到原始数据框:

    final_cat_features_df = pd.DataFrame(final_cat_features, index=df.index)
    df = df.join(final_cat_features_df)
    

    作为替代方案,您可能想看看 pandas get_dummies

    【讨论】:

      猜你喜欢
      • 2016-01-07
      • 2020-08-31
      • 2017-11-02
      • 2015-12-19
      • 2015-02-21
      • 2018-08-11
      • 2017-08-13
      • 1970-01-01
      • 2017-01-01
      相关资源
      最近更新 更多