Mortafix
Mortafix

Reputation: 95

Build numpy matrix from a dictionary with coordinate and value

Hi guys I'm trying to build a Numpy matrix from two dictionary. First dict has an integer key and a float64 value; the other one has coordinate as key and a integer value references to key of the first dict.

The goal is to build a Numpy matrix with coordinate the key in the second dict and value the float value corresponding to the integer key.

dict_coord = {(0,0): 1, (0,1): 0, (0,2): 2,
              (1,0): 1, (1,1): 1, (1,2): 0,
              (2,0): 1, (2,1): 2, (2,2): 0}

dict_values = {0: 1.1232.., 1: 0.3523.., 2: -1.2421..}

result = np.array([[0.3523,1.1232,-1.2421],
                   [0.3523,0.3523,1.1232],
                   [0.3523,-1.2421,1.1232]])

I found the simplest solution, but it's too slow. I'm working with matrix with 300 x 784 cells and this algorithm takes ~110ms to complete.

import numpy as np

def build_matrix(dict_index,dict_values):
    mat_ret = np.zeros([300,784])
    for k,v in dict_index.items():
        mat_ret[k] = dict_values[v]
    return mat_ret

If you can help me find a better and plain solution to this problem, I'll be grateful!

Upvotes: 1

Views: 571

Answers (1)

Nils Werner
Nils Werner

Reputation: 36805

Given your dict_coord keys are always sorted in that way, you can simply transform both dicts to arrays and then index one with the other:

coord_array = np.asarray(list(dict_coord.values()))
values_array = np.asarray(list(dict_values.values()))

values_array[coord_array].reshape(3, 3)
# array([[ 0.3523,  1.1232, -1.2421],
#        [ 0.3523,  0.3523,  1.1232],
#        [ 0.3523, -1.2421,  1.1232]])

Upvotes: 1

Related Questions