0

How do i map a dictionary over lists of np.ndarrays?

I have a dictionary containing a range of keys and values. It looks something like this:

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

In addition, i have a list object containing a range of numpy arrays which looks like this:

[array([1,2,3]),
 array([4,3,5,6]),
 array([1,4,6,2,3])]

I want to map the dictionary over the arrays to replace each value in each array with its corresponding key value in the dictionary. It will yield something like this:

[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])]

Finally i want to take the mean of each array in the above structure and append this value to a data frame.

Any suggestions?

1
  • 2
    Have you tried anything yet? Commented Feb 12, 2018 at 12:20

1 Answer 1

1

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])]
Sign up to request clarification or add additional context in comments.

2 Comments

Perfect! it worked! How do i go from here if i want to get the sum of each array?
list(map(np.sum, lst)) should work. But if you have more questions, please update your original question / ask a new one. This way SO is useful to a wider audience. If this answer works, feel free to accept (tick on left).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.