如何将每个最大值更改为1,沿矩阵中的其他值0

  • 本文关键字:其他 最大值 python numpy
  • 更新时间 :
  • 英文 :


我具有形状 (10,10000)的矩阵。对于矩阵中的每一列,我想在最大值索引和其他值0处拥有一个1。有什么方法可以避免for循环?

这是使用numpy的一个选项。首先导入numpy并将您的矩阵转换为numpy数组:

import numpy as np
my_mat = np.asarray(my_original_mat)

现在是一个小矩阵的示例:

mat = np.random.randint(1, 10, size=(4, 4))
# array([[3, 9, 3, 1],
#       [1, 4, 2, 3],
#       [8, 4, 4, 2],
#       [7, 7, 3, 7]])
new_mat = np.zeros(mat.shape)  # our zeros and ones will go here
new_mat[np.argmax(mat, axis=0), np.arange(mat.shape[1])] = 1
# array([[0., 1., 0., 0.],
#        [0., 0., 0., 0.],
#        [1., 0., 1., 0.],
#        [0., 0., 0., 1.]])

基本上使用Numpy切片来解决循环。new_mat[np.argmax(...), np.arange(...)]行指定每列,该行包含最大值,并将这些行柱对设置为1。似乎有效。

请注意,如果您重复了最大值,则仅将第一个(最高)最大值设置为1。

另一个为您提供1 s的选项,每个最大值,包括重复的值(我看到jdehesa在评论中击败了我,但在这里重复以完整性):

(mat == mat.max(axis=0)).astype(mat.dtype)

实际上很容易在稀疏存储中创建此矩阵。

>>> from scipy.sparse import csc_matrix
>>> 
>>> m, n = 3, 7
>>> 
>>> data = np.random.randint(0, 10, (m, n))
>>> 
>>> data
array([[9, 0, 0, 7, 3, 1, 3],
       [8, 0, 4, 4, 3, 2, 4],
       [2, 3, 2, 5, 7, 5, 3]])
>>> 
>>> result = csc_matrix((np.ones(n), data.argmax(0), np.arange(n+1)), (m, n))
>>> result
<3x7 sparse matrix of type '<class 'numpy.float64'>'
        with 7 stored elements in Compressed Sparse Column format>
>>> result.A
array([[1., 0., 0., 1., 0., 0., 0.],
       [0., 0., 1., 0., 0., 0., 1.],
       [0., 1., 0., 0., 1., 1., 0.]])

最新更新