对大量分类数据进行标签编码
我有一个包含 39 个分类特征和 27 个数字特征的数据集。我正在尝试对分类数据进行编码,并且需要能够进行逆变换并再次为每列调用转换。有没有比定义 39 个单独的 LabelEncoder 实例,然后分别对每一列进行 fit_transform 更漂亮的方法?
我觉得我错过了一些明显的东西,但我无法弄清楚!
enc = LabelEncoder
cat_feat = [col for col in input_df2.columns if input_df2[col].dtype == 'object']
cat_feat = np.asarray(cat_feat)
le1 =LabelEncoder()
le2 =LabelEncoder()
le3 =LabelEncoder()
...
#extended to le39
def label(input):
input.iloc[:, 1] = le1.fit_transform(input.iloc[:, 1])
input.iloc[:, 3] = le1.fit_transform(input.iloc[:, 3])
input.iloc[:, 4] = le1.fit_transform(input.iloc[:, 4])
...
return input
I have a dataset with 39 categorical and 27 numerical features. I am trying to encode the categorical data and need to be able to inverse transform and call transform for each column again. Is there a prettier way of doing it than defining 39 separate LabelEncoder instances, and then fit_transform to each column individually?
I feel like I am missing something obvious, but I cant figure it out!
enc = LabelEncoder
cat_feat = [col for col in input_df2.columns if input_df2[col].dtype == 'object']
cat_feat = np.asarray(cat_feat)
le1 =LabelEncoder()
le2 =LabelEncoder()
le3 =LabelEncoder()
...
#extended to le39
def label(input):
input.iloc[:, 1] = le1.fit_transform(input.iloc[:, 1])
input.iloc[:, 3] = le1.fit_transform(input.iloc[:, 3])
input.iloc[:, 4] = le1.fit_transform(input.iloc[:, 4])
...
return input
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
DataFrame.apply
就是为了这个。它将为数据帧的每一列(或每一行,如果您传递它axis=1
)调用指定的函数:DataFrame.apply
is just for this. It will call the specified function for each column of the dataframe (or each row, if you pass itaxis=1
):