【发布时间】:2021-07-22 08:37:32
【问题描述】:
假设我有一个如下所示的数据框
df = pd.DataFrame({'animal': ['Dog', 'Bird', 'Dog', 'Cat'],
'color': ['Black', 'Blue', 'Brown', 'Black'],
'age': [1, 10, 3, 6],
'pet': [1, 0, 1, 1],
'sex': ['m', 'm', 'f', 'f'],
'name': ['Rex', 'Gizmo', 'Suzy', 'Boo']})
我想使用标签编码器对“动物”、“颜色”、“性别”和“名称”进行编码,但我不需要对其他两列进行编码。我还希望能够在之后对列进行 inverse_transform。
我尝试了以下方法,尽管编码按我的预期工作,但反转却不行。
to_encode = ["animal", "color", "sex", "name"]
le = LabelEncoder()
for col in to_encode:
df[col] = fit_transform(df[col])
## to inverse:
for col in to_encode:
df[col] = inverse_transform(df[col])
inverse_transform 函数产生以下数据帧:
| animal | color | age | pet | sex | name |
|---|---|---|---|---|---|
| Rex | Boo | 1 | 1 | Gizmo | Rex |
| Boo | Gizmo | 10 | 0 | Gizmo | Gizmo |
| Rex | Rex | 3 | 1 | Boo | Suzy |
| Gizmo | Boo | 6 | 1 | Boo | Boo |
这显然不对,但我不确定我还能如何做到这一点?
任何建议将不胜感激!
【问题讨论】:
-
听起来像是
ColumnTransformer的工作!
标签: python pandas scikit-learn label-encoding