假设我有以下数据
import pandas as pd
data = {
'Reference': [1, 2, 3, 4, 5],
'Brand': ['Volkswagen', 'Volvo', 'Volvo', 'Audi', 'Volkswagen'],
'Town': ['Berlin', 'Berlin', 'Stockholm', 'Munich', 'Berlin'],
'Mileage': [35000, 45000, 121000, 35000, 181000],
'Year': [2015, 2014, 2012, 2016, 2013]
}
df = pd.DataFrame(data)
我想对“品牌”和“城镇”两列进行一次性编码,以便训练分类器(比如使用 Scikit-Learn)并预测年份。
训练分类器后,我将要预测新传入数据的年份(未在训练中使用),我将需要重新应用相同的热编码。例如:
new_data = {
'Reference': [6, 7],
'Brand': ['Volvo', 'Audi'],
'Town': ['Stockholm', 'Munich']
}
在这种情况下,知道需要对多个列进行编码并且需要能够应用相同的 Pandas DataFrame 上的 2 列的最佳方法是什么稍后对新数据进行编码。
这是 How to re-use LabelBinarizer for input prediction in SkLearn 的后续问题
最佳答案
演示:
from sklearn.preprocessing import LabelBinarizer
from collections import defaultdict
d = defaultdict(LabelBinarizer)
In [7]: cols2bnrz = ['Brand','Town']
In [8]: df[cols2bnrz].apply(lambda x: d[x.name].fit(x))
Out[8]:
Brand LabelBinarizer(neg_label=0, pos_label=1, spars...
Town LabelBinarizer(neg_label=0, pos_label=1, spars...
dtype: object
In [10]: new = pd.DataFrame({
...: 'Reference': [6, 7],
...: 'Brand': ['Volvo', 'Audi'],
...: 'Town': ['Stockholm', 'Munich']
...: })
In [11]: new
Out[11]:
Brand Reference Town
0 Volvo 6 Stockholm
1 Audi 7 Munich
In [12]: pd.DataFrame(d['Brand'].transform(new['Brand']), columns=d['Brand'].classes_)
Out[12]:
Audi Volkswagen Volvo
0 0 0 1
1 1 0 0
In [13]: pd.DataFrame(d['Town'].transform(new['Town']), columns=d['Town'].classes_)
Out[13]:
Berlin Munich Stockholm
0 0 0 1
1 0 1 0
关于python - 如何在 Pandas DataFrame 的多个列中进行一次性编码以供以后与 Scikit-Learn 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46675870/