python - 如何在 Pandas DataFrame 的多个列中进行一次性编码以供以后与 Scikit-Learn 一起使用

标签 python pandas scikit-learn

假设我有以下数据

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 的后续问题

最佳答案

考虑 the following approach .

演示:

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/

相关文章:

python - SWIG - python 中的 C++ 代码

python - 如何从 pandas 数据框中的特定列写入多个 Excel 工作表?

python - 如何绘制文本 K 均值聚类的结果?

python - scikit-learn joblib : Permission error importing, 在串行模式下运行

python-3.x - 使用 kmeans (sklearn) 对新文本进行预测?

python - 为多个 xarray 图制作带有修复颜色条的干净高质量 GIF

Python:使用协程进行异步 HTTP 请求-响应?

python - 分组并填充缺失的日期时间值

python - 如何识别 Pandas DataFrame 中列的行中的字符串重复?

python - 使用 Flask 将任意值打印到 Web 服务器