python - 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)
解决方案
这是最简单的方法:
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:]])
推荐阅读
- c - 如何使用滚动条在 GTK3 区域中绘制
- c - 您可以在 Arduino IDE 中打开和编辑 .c 文件吗?然后将它们加载到 Arduino 板上
- javascript - 如何使用 getJSON 填充下拉选择元素
- amazon-web-services - Do I have to use AppSync for apollo graphql in lambda?
- git - 并非所有工作空间中的项目都会在 GIT 中记录更改
- linux - 如何使用 GStreamer 从 IP RTMP 摄像机流式传输到 v4l2loopback 摄像机?
- php - 使用 PHP 从 MySql 获取具有给定 ID 的特定行
- flutter - 使用默认值初始化类参数
- php - PHP:计数和求和关联数组
- python - 如何递归地遍历 xml 文件并访问子节点/元素并使用 Python 存储它们的数据?