如何将 n 列标签数组转换为 1 列?

时间:2021-01-24 10:12:48

标签: python numpy

这是我在分类模型中使用的标签数组:

array([[1, 0, 0],
   [0, 1, 0],
   [0, 0, 1]], dtype=uint8)

但我想将其反转为一列,因此它看起来像这样:

  array([[0],
   [1],
   [2]], dtype=uint8)

感谢任何建议。

3 个答案:

答案 0 :(得分:3)

您可以使用 np.argmax

np.argmax(arr, axis=1).reshape(arr.shape[0], 1).astype(np.int8)

# array([[0],
#        [1],
#        [2]], dtype=int8)

如果您想始终占据 ones 的位置:

np.argmax(arr==1, axis=1)

答案 1 :(得分:1)

如果您的原始数组中每行只有一个有效值(如您的示例中所示),并且假设您调用该数组 a,则可以使用 numpy's where() 函数,例如 np.where(a)并获取返回的第二个数组。例如。 np.where(a)[1]

这仅在您要省略的值为 0False 时有效。

第二个数组包含列中的值计算为 True 的位置。

答案 2 :(得分:1)

arr = np.array([[1,0,0], [0,1,0], [0,0,1]])

def pos(lis):
    return np.where(lis == 1)[0]

posvec = np.apply_along_axis(pos, 1, arr)
相关问题