尝试在 csv 文件中编码数据。课堂上的TA推荐sklearn中的LabelEncoder。有一列名称为education_level。我需要按“高、中、低”的顺序对其进行编码。但是 LabelEncoder.fit_transform 默认使用 ASCII 码,这意味着它将按照“高、低、中”的顺序进行编码。
找不到使用自定义顺序对其进行编码的方法。下面附上代码。
# -*- coding: utf-8 -*-
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn import preprocessing
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn import metrics
# load train.csv
df = pd.read_csv('./train.csv')
objfeatures = df.select_dtypes(include="object").columns
le = preprocessing.LabelEncoder()
# Use Label Encoder
# TODO
# Any Better Way to encode the data? How to deal with missing values
for feat in objfeatures:
df[feat] = le.fit_transform(df[feat].astype(str))