numpy:从(索引,值)字典创建数组 [英] numpy: create array from a (index,value) dict

查看:183
本文介绍了numpy:从(索引,值)字典创建数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 dict 格式: {1:5,2:1,1,4:6,8:9}
,我想将其转换为以下形式的数组: [0,5,1,0,6,0,0,0,9]

因此,键表示数组的索引,而这些索引处的 dict 的值是

So the keys represent indexes into the array and the values of the dict at those indexes are the values of the array at the index.

是否有一种很好的快捷方式使用numpy做到这一点?

Is there a nice and quick way to do this with numpy?

推荐答案

就像 dict.get 一样简单。

>>> np.array([d.get(i, 0) for i in range(max(d) + 1)])
array([0, 5, 1, 0, 6, 0, 0, 0, 9])

这篇关于numpy:从(索引,值)字典创建数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆