pandas 将所有字符串转换为数字(一种热编码)以进行回归

pandas turning all strings into numbers ( one hot encoding) for regression

我正在尝试预处理如下所示的数据:

train.head(4)

    Id  MSSubClass  MSZoning    LotFrontage LotArea Street  Alley   LotShape    LandContour Utilities   ... PoolArea    PoolQC  Fence   MiscFeature MiscVal MoSold  YrSold  SaleType    SaleCondition   SalePrice
0   1.0 60.0    RL  65.0    8450    Pave    NaN Reg Lvl AllPub  ... 0   NaN NaN NaN 0   2   2008    WD  Normal  208500
1   2.0 20.0    RL  80.0    9600    Pave    NaN Reg Lvl AllPub  ... 0   NaN NaN NaN 0   5   2007    WD  Normal  181500
2   3.0 60.0    RL  68.0    11250   Pave    NaN IR1 Lvl AllPub  ... 0   NaN NaN NaN 0   9   2008    WD  Normal  223500
3   4.0 70.0    RL  60.0    9550    Pave    NaN IR1 Lvl AllPub  ... 0   NaN NaN NaN 0   2   2006    WD  Abnorml 140000
4 rows × 81 columns

我必须找到一种方法将这些字符串转换为数字,以便我可以将它们用于回归。我也知道如果我简单地给它们编号,我可能会引入错误的距离逻辑(不是热编码)。有人知道一个聪明的方法吗?

N

您可以尝试pandas.get_dummies()对分类数据进行编码。您可以查看文档 here。它不会转换您的整数值(即,它将保持原样。请参阅官方文档中的示例)。

df = pd.DataFrame({'A': ['a', 'b', 'a'], 'B': ['b', 'a', 'c'],
                    'C': [1, 2, 3]})

pd.get_dummies(df, prefix=['col1', 'col2'])
   C  col1_a  col1_b  col2_a  col2_b  col2_c
0  1       1       0       0       1       0
1  2       0       1       1       0       0
2  3       1       0       0       0       1

如果分类特征的数量很大并且每个分类的唯一值的数量也很大,您可以尝试 Scikit-learn 的 DictVectorizer。请参阅文档 here .

您可以检查 this link 以了解根据您的算法使用哪种编码。