Converting a Numpy Array into a Dict of Values Mapped to Rows

Converting a numpy array into a dict of values mapped to rows

You can use collections.defaultdict, before using OrderedDict to sort by number of observations:

import numpy as np
from collections import defaultdict, OrderedDict

A = np.array([[1, 2, 3],
[1, 0, 0],
[1, 3, 0]])

d = defaultdict(list)

for idx, row in enumerate(A):
for i in set(row):
d[i].append(idx)

res = OrderedDict(sorted(d.items(), key=lambda x: len(x[1]), reverse=True))

print(res)

OrderedDict([(1, [0, 1, 2]),
(3, [0, 2]),
(0, [1, 2]),
(2, [0])])

Convert a Numpy 2 dimensional array to a mapped list of dictionaries

Use zip + dict:

result = [dict(zip(headers, l)) for l in A]
print(result)

Output

[{'a': 1, 'b': 2, 'c': 3}, {'a': 4, 'b': 5, 'c': 6}]

With zip you create pair of items from the list and pass it to the dictionary constructor.

How to assign each row in a numpy array into keys in dictionary python

If a tuple will do, then:

import numpy as np

my_array = np.array([[5.8, 2.7, 3.9, 1.2],
[5.6, 3., 4.5, 1.5],
[5.6, 3., 4.1, 1.3]])


d = { k : None for k in map(tuple, my_array)}

print(d)

Output

{(5.8, 2.7, 3.9, 1.2): None, (5.6, 3.0, 4.5, 1.5): None, (5.6, 3.0, 4.1, 1.3): None}

As an alternative, you could do:

d = { tuple(row) : None for row in my_array}

Translate every element in numpy array according to key

I don't know about efficient, but you could use np.vectorize on the .get method of dictionaries:

>>> a = np.array([[1,2,3],
[3,2,4]])
>>> my_dict = {1:23, 2:34, 3:36, 4:45}
>>> np.vectorize(my_dict.get)(a)
array([[23, 34, 36],
[36, 34, 45]])

Pythonic way to convert a dictionary to a numpy array

Try a pandas Series, it was built for this.

import pandas as pd
s = pd.Series({'a':1, 'b':2, 'c':3})
s.values # a numpy array

How to convert Numpy Array to Python Dictionary with Sequential Keys?

Use flatten and then create the dictionary with the help of enumerate starting from 1:

myarray = np.array([[0,400,405,411,415,417,418,0],
[0,404,412,419,423,422,422,0],
[0,409,416,421,424,425,425,0],
[0,411,414,417,420,423,426,0],
[0,409,410,410,413,419,424,0],
[0,405,404,404,409,414,419,0]])

d = dict(enumerate(myarray.flatten(), 1))

Output of d:

{1: 0,
2: 400,
3: 405,
4: 411,
5: 415,
6: 417,
7: 418,
8: 0,
9: 0,
10: 404,
...

How to apply dictionary with array as value in numpy array

You can use a list comprehension and feed to np.array:

res = np.array([list(map(d.__getitem__, row)) for row in target])

array([[[ 1, 1, 0, 0, 0],
[ 0, 0, 0, 0, 0],
[ 1, 1, 0, 0, 0],
...
[ 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0],
[ 1, 1, 0, 0, 0]],

[[ 1, 1, 1, 1, 0],
[ 1, 1, 1, 1, 0],
[ 1, 1, 1, 0, 0],
...
[-1, -1, 0, 0, 0],
[-1, -1, -1, 0, 0],
[-1, -1, -1, -1, 0]]])

Note the dictionary has been renamed d: don't shadow built-ins.

Python: Mapping dictionary over multiple np.arrays

This is one solution.

import numpy as np

d = {1: 0.5,
2: 0.51,
3: 0.34,
4: 0.38,
5: 0.4,
6: 0.27,}

lst = [np.array([1,2,3]),
np.array([4,3,5,6]),
np.array([1,4,6,2,3])]

lst2 = list(map(np.vectorize(d.get), lst))

# [array([ 0.5 , 0.51, 0.34]),
# array([ 0.38, 0.34, 0.4 , 0.27]),
# array([ 0.5 , 0.38, 0.27, 0.51, 0.34])]

Numpy: Convert values in a 1-D array based upon dictionary

Here are a couple ideas.

First, define some sample data:

In [36]: data = np.array(['a', 'b', 'a', 'a', 'c', 'b'])

In [37]: mapping = {'a': 9, 'b': 0, 'c': 5}

You can use numpy.unique to get the unique elements in data, and (more importantly) an array that maps those unique values back to the input array:

In [38]: keys, inv = np.unique(data, return_inverse=True)

At this point, keys[inv] recreates data. But we want to create the mapped array, so we'll make an array of the values in mapping, in the same order as the keys returned by np.unique:

In [39]: vals = np.array([mapping[key] for key in keys])

Now we can index vals with inv to get the desired result:

In [40]: result = vals[inv]

In [41]: result
Out[41]: array([9, 0, 9, 9, 5, 0])

Another approach, this one fairly straightforward, is to simply loop over the keys in mapping, and do a vectorized assignment of the values into a new array:

In [42]: result = np.empty(data.size, dtype=int)

In [43]: for key, val in mapping.items():
....: result[data == key] = val
....:

In [44]: result
Out[44]: array([9, 0, 9, 9, 5, 0])

Without know more about the actual size of data and the number of keys in mapping, it is hard to say which method will be more efficient.

Here's a method you probably won't want to use, because the 2-d intermediate array formed by the expression data.reshape(-1, 1) == keys will have shape (len(data), len(mapping)):

In [63]: keys = np.array(mapping.keys())

In [64]: vals = np.array(mapping.values())

In [65]: result = vals[(data.reshape(-1, 1) == keys).nonzero()[1]]

In [66]: result
Out[66]: array([9, 0, 9, 9, 5, 0])

How to get values from a map and set them into a numpy matrix row?

You can simply get the values form your dictionary and then use np.full to create your 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.]])

And if the method function returns different results in each iteration, you can use a list comprehension to create your matrix:

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

NOTE: Since your dictionary keys are sorted digits and in this case your keys have a sorted hash value, the dict.values method returns a sorted value based on your keys:

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

If your keys are not sorted digits, you can make your method functions return an ordered dictionary using collections.OrderedDict.

But note that since OrderedDict is ordered by insertion, if that is what you want, you can use it. However if you want to order based on keys, you can use the following approach to get the values:

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


Related Topics



Leave a reply



Submit