给定一个列索引i和一个稀疏的scipy csr矩阵X,我想得到在列i处有1的所有行的平均向量
这是我提出的解决方案,但在我看来相当缓慢:
# a) create a mask of rows containing True if this column was > 0 or False otherwise
mask = (X[:, i] > 0).transpose().toarray()[0]
# b) now get the indices of these rows as list
indices_of_row = list(np.where(mask > 0)[0])
if len(indices_of_row) == 0:
return
# c) use the indices of these rows to create the mean vector
mean_vector = X[indices_of_row,].mean(axis=0)
有没有办法让它更有效或者更可读
编辑:我希望避免对整个矩阵调用toarray()
我想这就够了
编辑
以下是三种相对快速的解决方案:
运行示例:
相关问题 更多 >
编程相关推荐