简体   繁体   English

如何从非零元素的索引字典创建稀疏 numpy 数组?

[英]How to create a sparse numpy array from a dictionary of indices for nonzero elements?

I have a dictionary of indices corresponding to nonzero numbers, and want to write a function that creates an sparse array with nonzero elements at the given indices, with zeros in between.我有一个对应于非零数字的索引字典,并想编写一个 function 来创建一个稀疏数组,该数组在给定索引处具有非零元素,中间有零。 Ex:前任:

{(0,0):2, (1,1):3}

would output to the following numpy array将 output 到以下 numpy 数组

([[2,0], [0,3]])

What would be the simplest way to convert this dense dictionary into a sparse array?将这个密集字典转换为稀疏数组的最简单方法是什么?

This should work, the only thing you need, you should know the dimensions for your output.这应该可行,您唯一需要的,您应该知道 output 的尺寸。

import numpy as np

d = {(0,0):2, (1,1):3}

S = 2
table = np.zeros((S,S))

for k,v in d.items():
    if d[k]:
        table[ k[0],k[1] ] = v

print(table)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM