6

I have a dictionary with datetime months as keys and lists of floats as values, and I'm trying to convert the lists into numpy arrays and update the dictionary. This is my code so far:

def convert_to_array(dictionary):
'''Converts lists of values in a dictionary to numpy arrays'''
rv = {}
for v in rv.values():
    v = array(v)

5 Answers 5

7

You can use fromiter to get the keys and values into an np array:

import numpy as np

Samples = {5.207403005022627: 0.69973543384229719, 
        6.8970222167794759: 0.080782939731898179, 
        7.8338517407140973: 0.10308033284258854, 
        8.5301143255505334: 0.018640838362318335, 
        10.418899728838058: 0.14427355015329846, 
        5.3983946820220501: 0.51319796560976771}

keys = np.fromiter(Samples.keys(), dtype=float)
vals = np.fromiter(Samples.values(), dtype=float)

print(keys)
print('-'*20)
print(vals)
Sign up to request clarification or add additional context in comments.

Comments

0

You can do this with a small dict comprehension.

import numpy as np

def convert_to_array(dictionary):
    '''Converts lists of values in a dictionary to numpy arrays'''
    return {k:np.array(v) for k, v in dictionary.items()}

d = {
    'date-1': [1.23, 2.34, 3.45, 5.67],
    'date-2': [54.47, 45.22, 22.33, 54.89],
    'date-3': [0.33, 0.589, 12.654, 4.36]
}

print(convert_to_array(d))
# {'date-1': array([1.23, 2.34, 3.45, 5.67]), 'date-2': array([54.47, 45.22, 22.33, 54.89]), 'date-3': array([ 0.33 ,  0.589, 12.654,  4.36 ])}

Comments

0

See numpy.asarray (https://docs.scipy.org/doc/numpy/reference/generated/numpy.asarray.html). This converts list-like structures into ndarrays.

Comments

0

You can try this in your function:

import numpy as np
for key, value in dictionary.items():
    dictionary[key] = np.asarray(value)

numpy.asarray to transform your lists into an arrays and update your dictionary at the same time.

Comments

-1

This is how you can do it:

myDict = {637.0: [139.0, 1.8, 36.0, 18.2], 872.0: [139.0, 1.8, 36.0, 18.2]}
y = np.zeros(len(myDict))
X = np.zeros((len(myDict), 4))
i = 0
for key, values in myDict.items():
    y[i] = key
    X[i, :] = values
    i += 1

Comments

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.