python - 按列向量化二维字符数组

标签 python numpy scikit-learn

我有一个二维 numpy 数组,如下所示:

a=np.array([["Science", "Blue", 3],
            ["Math", "Red", 4],
            ["Math", "Red", 5],
            ["Science", "Red", 3]])

我需要按列将其转换为数值,如下所示(所需输出):

out=np.array([[0, 0, 0],
              [1, 1, 1],
              [1, 1, 2], 
              [0, 1, 0]])

但是,为了下游的可解释性,我还需要一个输出来从数值追溯到原始值。我在想这样的事情:

trace_back_dict = {0: {0: "Science", 1: "Math"}, 
                   1: {0: "Blue", 1: "Red"}, 
                   2: {0: 3, 1: 4, 2: 5}}

其中外部键是原始数组的列索引,内部字典给出数字:字符值的映射。

有没有一种简单的方法可以做到这一点,最好是 sklearn 风格的东西,在那里我可以做一个 fit_transform,然后 transform (用于训练和测试集目的)?

我正在查看 sklearnLabelEncoder,基本上我需要的是在每一列上应用不同的编码器。关于如何有效地执行此操作的任何建议?

谢谢!

jack

最佳答案

你可以使用 OrdinalEncoder :

In [25]: a = [['Science', 'Blue', 3], ['Math', 'Red', 4], ['Math', 'Red', 5], ['Science', 'Red', 3]]

In [26]: enc = sklearn.preprocessing.OrdinalEncoder()

In [27]: enc.fit(a)
Out[27]: OrdinalEncoder(categories='auto', dtype=<class 'numpy.float64'>)

In [28]: enc.transform(a)
Out[28]: 
array([[1., 0., 0.],
       [0., 1., 1.],
       [0., 1., 2.],
       [1., 1., 0.]])

In [29]: enc.categories_
Out[29]: 
[array(['Math', 'Science'], dtype=object),
 array(['Blue', 'Red'], dtype=object),
 array([3, 4, 5], dtype=object)]

In [30]: trace_back_dict = {i: dict(enumerate(v)) for i, v in enumerate(enc.categories_)}

In [31]: trace_back_dict
Out[31]: {0: {0: 'Math', 1: 'Science'}, 1: {0: 'Blue', 1: 'Red'}, 2: {0: 3, 1: 4, 2: 5}}

关于python - 按列向量化二维字符数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53142301/

相关文章:

尽管有逗号,python 打印语句打印换行符

python - 用多个分隔符分割Python字符串

python - PIL属性错误: Shape when creating an array

python - 在 Python 的日期列表中获取每个月的最后一个日期

python - python中的线性回归严重错误,回归线完全错误

python - 导入错误 : No module named model_selection

python - pandas 中导入 Excel 文件的多重索引问题

python - Pandas 查找最接近配置文件的行

python - NumPy Matrix 与 Array 类的乘法有何不同?

python - 导入错误 : cannot import name murmurhash3_32