我有一個包含 m 行和數組作為值的數組,它們指示列的索引并限制為一個大數 n。例如: Y = [[1,34,203,2032],...,[2984]]現在我想要一種有效的方法來初始化一個稀疏的 numpy 矩陣 X,其維度為 m,n,值對應于 Y(X[i,j] = 1,如果 j 在 Y[i] 中,否則 = 0)。
1 回答

繁星coding
TA貢獻1797條經驗 獲得超4個贊
您的數據已經接近 csr 格式,所以我建議使用它:
import numpy as np
from scipy import sparse
from itertools import chain
# create an example
m, n = 20, 10
X = np.random.random((m, n)) < 0.1
Y = [list(np.where(y)[0]) for y in X]
# construct the sparse matrix
indptr = np.fromiter(chain((0,), map(len, Y)), int, len(Y) + 1).cumsum()
indices = np.fromiter(chain.from_iterable(Y), int, indptr[-1])
data = np.ones_like(indices)
S = sparse.csr_matrix((data, indices, indptr), (m, n))
# or
S = sparse.csr_matrix((data, indices, indptr))
# check
assert np.all(S==X)
添加回答
舉報
0/150
提交
取消