这个问题在这里已有答案:
简单的问题,我想获得1D numpy数组。
给定一个2D数组,其中每行包含一个'1'值,如何将其转换为一维数组,由二维数组中的'1'的列索引组成
[[ 0. 0. 1.]
[ 0. 0. 1.]
[ 0. 0. 1.]
[ 0. 1. 0.]
[ 0. 1. 0.]
[ 0. 1. 0.]
[ 0. 1. 0.]
[ 1. 0. 0.]]
至
[2 2 1 1 1 1 0]
我怎么能在python中做到这一点?我不知道它的术语,让我知道这种转换的正确术语。
您正在寻找沿第一轴具有最大值的索引:
>>> a.argmax(axis=1)
array([2, 2, 2, 1, 1, 1, 1, 0])
a.argmax(axis=None, out=None)
返回给定轴上的最大值的索引。
如果其他值不一定小于1,则首先过滤1
。这给出了True
和False
值的数组。现在,使用argmax()
:
>>> (a == 1).argmax(axis=1)
array([2, 2, 2, 1, 1, 1, 1, 0])
True
像1
一样充当False
和0
,因为bool
继承自int
。
好像你想获得每行一个热编码矢量的热索引。
这可以按如下方式完成:
[0 1 2]
,或更通用:numpy.arange(matrix.shape[1])
numpy.sum(matrix, axis=1)
numpy数组也有argmax
函数,导致相同的结果。
您可以使用numpy argmax执行此操作,如下所示:
a=np.array([[ 0, 0, 1],[ 0, 0, 1], [ 0, 0, 1],[ 0, 1, 0],[ 0, 1, 0],[ 0, 1, 0],[ 1,0,0]])
a.argmax(1)
array([2, 2, 2, 1, 1, 1, 0])