[英]Convert dictionary values to numpy arrays
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. 我有一本以datetime月作为键,而浮点数列表作为值的字典,并且我试图将这些列表转换成numpy数组并更新字典。 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)
You can use fromiter
to get the keys and values into an np array: 您可以使用
fromiter
将键和值放入np数组中:
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)
You can do this with a small dict comprehension. 您可以通过少量的dict理解来做到这一点。
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 ])}
See numpy.asarray
( https://docs.scipy.org/doc/numpy/reference/generated/numpy.asarray.html ). 请参阅
numpy.asarray
( https://docs.scipy.org/doc/numpy/reference/generated/numpy.asarray.html )。 This converts list-like structures into ndarrays. 这会将类似列表的结构转换为ndarray。
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. numpy.asarray
将您的列表转换成数组并同时更新字典。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.