首页 > 解决方案 > How do I load a file into a dictionary where key:text, val: numpy array of floats?

问题描述

The file I wish to use is in the format;

a, 1.1, 2.2, 3.3, 4.4
b, 5.5, 6.6, 7.7, 8.8
c, 9.9, ..., ..., ...

and I need to convert this to a dictionary Keys by the first column with associated values being numpy array of 4 digits. This is running on python 3.

So far I have tried to separate them into two data sets using line.split but I am not sure where to go from here or if this is even right:

d = {}
with open("filex.csv") as f:
    for line in f:
        (key, val) = line.split(",", 1)

标签: pythonnumpy

解决方案


这是最简单的方法:

import numpy as np
d = {}
with open("filex.csv") as f:
    for line in f:
        splits = line.split(",")
        key = splits[0]
        d[key] = np.array([s.strip() for s in splits[1:]])

推荐阅读