2 回答

TA貢獻1799條經驗 獲得超9個贊
這是使用 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。
另一個選項可以為每個最大值提供 1s ,包括重復的值(我看到 jdehesa 在評論中擊敗了我,但為了完整起見在這里重復):
(mat == mat.max(axis=0)).astype(mat.dtype)

TA貢獻1850條經驗 獲得超11個贊
在稀疏存儲中創建這個矩陣實際上很容易。
>>> 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.]])
添加回答
舉報