【问题标题】:One-hot encode a column of integers into a NumPy matrix, including missing indicesOne-hot 将一列整数编码为 NumPy 矩阵,包括缺失的索引
【发布时间】:2021-11-28 18:47:25
【问题描述】:

来自以下 NumPy 数组:

[5, 2, 4, 6, 3]

我想得到以下矩阵:

[
    [0, 0, 0, 0, 0, 1, 0],
    [0, 0, 1, 0, 0, 0, 0],
    [0, 0, 0, 0, 1, 0, 0],
    [0, 0, 0, 0, 0, 0, 1],
    [0, 0, 0, 1, 0, 0, 0]
]

使用 Pandas get_dummies 看起来很简单:

pd.get_dummies(original_array).values

但它有一个缺点,即缺失的索引在最终矩阵中不表示为列(例如,本例中的 0、1)。

如果我们假设预先知道所需“列”的确切名称/索引(这里包括从 0 到 6 的所有整数),那么获取上述矩阵的最有效方法是什么,从从初始数组?

【问题讨论】:

标签: python pandas numpy one-hot-encoding


【解决方案1】:

您可以创建一个 zeros 矩阵,然后使用高级索引将一个分配给正确的列:

a = [5, 2, 4, 6, 3]

ohe = np.zeros((len(a), max(a) + 1), dtype=int)
ohe[np.arange(len(a)), a] = 1

ohe
array([[0, 0, 0, 0, 0, 1, 0],
       [0, 0, 1, 0, 0, 0, 0],
       [0, 0, 0, 0, 1, 0, 0],
       [0, 0, 0, 0, 0, 0, 1],
       [0, 0, 0, 1, 0, 0, 0]])

【讨论】:

    【解决方案2】:

    高级索引是您的答案!假设你知道你想要的最终形状(这里是(5, 7)):

    In [5]: desired_shape = (5, 7)
    
    In [6]: z = np.zeros(desired_shape, dtype="uint8")
    
    In [5]: z
    Out[5]:
    array([[0, 0, 0, 0, 0, 0, 0],
           [0, 0, 0, 0, 0, 0, 0],
           [0, 0, 0, 0, 0, 0, 0],
           [0, 0, 0, 0, 0, 0, 0],
           [0, 0, 0, 0, 0, 0, 0]], dtype=uint8)
    
    In [6]: idxs = [5, 2, 4, 6, 3]
    
    In [7]: z[range(len(z)), idxs] = 1
    
    In [8]: z
    Out[8]:
    array([[0, 0, 0, 0, 0, 1, 0],
           [0, 0, 1, 0, 0, 0, 0],
           [0, 0, 0, 0, 1, 0, 0],
           [0, 0, 0, 0, 0, 0, 1],
           [0, 0, 0, 1, 0, 0, 0]], dtype=uint8)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-26
      • 2023-03-13
      • 2020-11-21
      • 2022-01-22
      • 2022-08-05
      相关资源
      最近更新 更多