How to get values ​​from a map and set them to a numeric matrix string?

I have a numpy matrix that I want to populate with the results of a function. This function returns a map of integer values ​​that will be displayed in the matrix row.

The values ​​returned by the function are as follows:

{1:6, 2:3, 3:2, 4:2, 5:1}

Then I wrote the following code to populate the values ​​in the matrix:

results = np.empty((10, 5), dtype=int)

for i in range(10):
    result = method()
    for j in range(5):
        results[i, j] = result[j]

I want to know if there is a more efficient / efficient way to do this with python?

+4
source share
2 answers

You can simply get the values ​​from your dictionary and then use np.fullto create the expected matrix:

>>> d={1:6, 2:3, 3:2, 4:2, 5:1}
>>> vals=d.values()
>>> np.full((10,5),list(vals))
array([[ 6.,  3.,  2.,  2.,  1.],
       [ 6.,  3.,  2.,  2.,  1.],
       [ 6.,  3.,  2.,  2.,  1.],
       [ 6.,  3.,  2.,  2.,  1.],
       [ 6.,  3.,  2.,  2.,  1.],
       [ 6.,  3.,  2.,  2.,  1.],
       [ 6.,  3.,  2.,  2.,  1.],
       [ 6.,  3.,  2.,  2.,  1.],
       [ 6.,  3.,  2.,  2.,  1.],
       [ 6.,  3.,  2.,  2.,  1.]])

method , :

l = np.array([list(method().values()) for _ in range(1, 11)])

. , -, dict.values :

>>> list(map(hash, range (1 , 6)))
[1, 2, 3, 4, 5]

, , collections.OrderedDict.

, OrderedDict , , , . , , :

[map(dict.get, range(1, 6)) for _ in range(10)]
+1

.

method() , results.

, d.keys().

Python3, keys values . fromiter ( np.array(list(d.keys()))

d={1:6, 2:3, 3:2, 4:2, 5:1}
results=np.empty((4,5), int)  # np.zeros better?
for i in range(results.shape[0]):
    result = d # method() 
    ind = np.fromiter(d.keys(), int)-1
    val = np.fromiter(d.values(), int)
    results[i, ind] = val

, , .

0

Source: https://habr.com/ru/post/1609644/


All Articles