从非零元素的索引字典创建稀疏numpy数组可以通过以下步骤实现:
import numpy as np
from scipy.sparse import coo_matrix
index_dict = {(0, 1): 2, (1, 2): 3, (2, 0): 4}
rows, cols, values = zip(*[(row, col, value) for (row, col), value in index_dict.items()])
sparse_matrix = coo_matrix((values, (rows, cols)))
sparse_array = sparse_matrix.toarray()
完整的代码示例如下:
import numpy as np
from scipy.sparse import coo_matrix
index_dict = {(0, 1): 2, (1, 2): 3, (2, 0): 4}
rows, cols, values = zip(*[(row, col, value) for (row, col), value in index_dict.items()])
sparse_matrix = coo_matrix((values, (rows, cols)))
sparse_array = sparse_matrix.toarray()
print(sparse_array)
这样,你就可以从非零元素的索引字典创建稀疏numpy数组了。
关于稀疏数组的概念、分类、优势和应用场景,以及腾讯云相关产品和产品介绍链接地址,可以参考以下内容:
腾讯云相关产品和产品介绍链接地址:
请注意,以上链接仅供参考,具体产品选择应根据实际需求进行评估。
没有搜到相关的结果
领取专属 10元无门槛券
手把手带您无忧上云