问题
I want to create a dict from lower triangle of a symmetric matrix represented as 2d array. For examples if the numpy array is;
array([[0, 2, 3],
[2, 0, 4],
[3, 4, 0]])
then I want the dict to look like;
{('1', '0'): 2, ('2', '0'): 3, ('2', '1'): 4}
There is a similar post for vector;
Fastest way to convert a Numpy array into a sparse dictionary?
I am relatively new to python so any help/suggestoins appreciated.
回答1:
>>> arr =[[0, 2, 3],
[2, 0, 4],
[3, 4, 0]]
>>> dict(((j,i), arr[i][j]) for i in range(len(arr)) for j in range(len(arr[0])) if i<j)
{(2, 0): 3, (1, 0): 2, (2, 1): 4}
回答2:
One way to do it is with ndenumerate and defaultdict.
Building a dict mapping each value to all its positions:
>>> d = defaultdict(list)
>>> for pos,val in numpy.ndenumerate(a):
... if val:
... d[val].append(pos[1])
...
>>> d
defaultdict(<class 'list'>, {2: [1, 0], 3: [2, 0], 4: [2, 1]})
And then reversing keys and values:
>>> {tuple(v):k for k,v in d.items()}
{(2, 0): 3, (1, 0): 2, (2, 1): 4}
If your python version does not support dict comprhension, this last part could be:
>>> dict((tuple(v),k) for k,v in d.iteritems())
{(2, 0): 3, (1, 0): 2, (2, 1): 4}
来源:https://stackoverflow.com/questions/9545139/python-2d-array-to-dict