【问题标题】:replace element in 1d numpy array with numpy array [duplicate]用numpy数组替换一维numpy数组中的元素[重复]
【发布时间】:2018-03-30 18:41:25
【问题描述】:

假设我有一个 numpy 数组x = np.array([0, 1, 2]),python 中是否有内置函数可以将元素转换为相应的数组?

例如 我想将x中的0转换为[1,0,0],1转换为[0,1,0],2转换为[0,0,1],预期输出为np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]])

我尝试了x[x == 0] = np.array([1, 0, 0]),但它不起作用。

【问题讨论】:

  • 你可以使用OneHotEncoder
  • 哦,是的,它是重复的。我发现该帖子的答案链接中有一个很好的答案,尽管问题的措辞确实不同,所以我没有找到它....好像我无法删除我的问题,所以我标记了它。

标签: python arrays numpy


【解决方案1】:

演示:

In [38]: from sklearn.preprocessing import OneHotEncoder

In [39]: ohe = OneHotEncoder()

# modern versions of SKLearn methods don't like 1D arrays
# they expect 2D arrays, so let's make it happy ;-)    
In [40]: res = ohe.fit_transform(x[:, None])

In [41]: res.A
Out[41]:
array([[ 1.,  0.,  0.],
       [ 0.,  1.,  0.],
       [ 0.,  0.,  1.]])

In [42]: res
Out[42]:
<3x3 sparse matrix of type '<class 'numpy.float64'>'
        with 3 stored elements in Compressed Sparse Row format>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-03
    • 2016-07-13
    • 1970-01-01
    • 2015-10-02
    • 2018-01-13
    相关资源
    最近更新 更多