我正在尝试对具有某些分类值特征的数据集进行逻辑回归。为了通过回归处理这些特征,我打算对其进行编码
#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列连接在一起,以便最终获得要添加到新数据框中的新功能?如果没有,我不得不说我被困在这里。
答案 0 :(得分:1)
您应该将所有290列与其余(即非分类或数字)值添加到数据框中。为此,您可以从数组创建一个数据框并将其连接到原始数据框:
final_cat_features_df = pd.DataFrame(final_cat_features, index=df.index)
df = df.join(final_cat_features_df)
或者,您可能想看看熊猫get_dummies
。