您可以在此处使用LabelEncoder。
import pandas as pd
df = pd.DataFrame({'prediction':['red', 'green', 'blue'], 'features': ['one','two','three']})
from sklearn import preprocessing
le = preprocessing.LabelEncoder()
le.fit(df["prediction"])
oldData = df['prediction'].tolist()
df["prediction"] = le.transform(df["prediction"])
new_df = pd.DataFrame({'prediction':['yellow', 'red', 'green'], 'features': ['three','two','one']})
newData = new_df['prediction'].tolist()
newData = list(set(newData)- set(oldData))
le.classes_ = np.append(le.classes_, newData )
new_df["prediction"] = le.transform(new_df["prediction"])
更新
import pandas as pd
df = pd.DataFrame({'prediction':['red', 'green', 'blue'], 'features': ['one','two','three']})
from sklearn import preprocessing
encoderDict = {}
oldData = {}
for col in df.columns:
le = preprocessing.LabelEncoder()
le.fit(df[col])
encoderDict[col] = le
oldData[col] = df[col].tolist()
df[col] = le.transform(df[col])
new_df = pd.DataFrame({'prediction':['yellow', 'red', 'green'], 'features': ['three','two','one']})
newData = {}
for col in new_df.columns:
newData[col] = new_df[col].tolist()
newData[col] = list(set(newData[col])- set(oldData[col]))
encoderDict[col].classes_ = np.append(encoderDict[col].classes_, newData[col] )
new_df[col] = encoderDict[col].transform(new_df[col])
要对数据进行逆变换,您只需执行以下操作。
ndf = df.append(new_df).reset_index(drop=True)
for col in ndf:
print(encoderDict[col].inverse_transform(ndf[col]))