Python 从 numpy 数组创建字典

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19991338/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 15:11:06  来源:igfitidea点击:

Creating dictionary from numpy array

pythonarraysdictionarynumpy

提问by user2926009

I have an numpy array and I want to create a dictionary from the array.

我有一个 numpy 数组,我想从该数组创建一个字典。

More specifically I want a dictionary that has keys that correspond to the row, so key 1 should be the sum of row 1.

更具体地说,我想要一个具有与行对应的键的字典,所以键 1 应该是第 1 行的总和。

s1 is my array and I know how to get the sum of the row but doing numpy.sum(s1[i]), where i is the row.

s1 是我的数组,我知道如何获得行的总和,但在numpy.sum(s1[i])那里我是行。

I was thinking of creating a loop where I can compute the sum of the row and then add it to a dictionary but I am new to programming so I am not sure how to do this or if it is possible.

我正在考虑创建一个循环,我可以在其中计算行的总和,然后将其添加到字典中,但我是编程新手,所以我不确定如何执行此操作或是否可能。

Does anybody have any suggestions?

有人有什么建议吗?

EDIT

编辑

I created the key values with the range function. Then zipped the keys and the array.

我用 range 函数创建了键值。然后压缩键和数组。

mydict = dict(zip(keys, s1))

采纳答案by DSM

I'd do something similar in spirit to your dict(zip(keys, s1)), with two minor changes.

我会做一些与你的精神相似的事情dict(zip(keys, s1)),但有两个小改动。

First, we can use enumerate, and second, we can call the summethod of ndarrays. Example:

首先,我们可以使用enumerate,其次,我们可以调用s的sum方法ndarray。例子:

>>> arr = np.arange(9).reshape(3,3)
>>> arr
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
>>> arr.sum(axis=1)
array([ 3, 12, 21])
>>> dict(enumerate(arr.sum(axis=1)))
{0: 3, 1: 12, 2: 21}