我有一个字典,其中datetime月份作为键,浮点数列表作为值,并且我正在尝试将列表转换为numpy数组并更新字典。以下是我的代码:
def convert_to_array(dictionary):
'''Converts lists of values in a dictionary to numpy arrays'''
rv = {}
for v in rv.values():
v = array(v)
我有一个字典,其中datetime月份作为键,浮点数列表作为值,并且我正在尝试将列表转换为numpy数组并更新字典。以下是我的代码:
def convert_to_array(dictionary):
'''Converts lists of values in a dictionary to numpy arrays'''
rv = {}
for v in rv.values():
v = array(v)
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)
你可以使用一个小的字典推导式来完成这个任务。
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 ])}
import numpy as np
for key, value in dictionary.items():
dictionary[key] = np.asarray(value)
numpy.asarray
将列表转换为数组,并同时更新您的字典。numpy.asarray
(https://docs.scipy.org/doc/numpy/reference/generated/numpy.asarray.html)。这将列表结构转换为ndarrays。这是你可以做到的方法:
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