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