Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating dictionary from numpy array

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

More specifically I want a dictionary that has keys that correspond to the row, so key 1 should be the sum of row 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.

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.

mydict = dict(zip(keys, s1))
like image 469
user2926009 Avatar asked Nov 15 '13 00:11

user2926009


People also ask

Can a numpy array be a dictionary key?

You may use the data in numpy array to create a hash which could be used as a key for dictionary.


1 Answers

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

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

>>> 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}
like image 81
DSM Avatar answered Sep 28 '22 11:09

DSM