将字典值转换为numpy数组

6

我有一个字典,其中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)
5个回答

5
您可以使用 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)

0

你可以使用一个小的字典推导式来完成这个任务。

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

0
你可以在你的函数中尝试这个:
import numpy as np
for key, value in dictionary.items():
    dictionary[key] = np.asarray(value)

使用 numpy.asarray 将列表转换为数组,并同时更新您的字典。

0

-1

这是你可以做到的方法:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接