我对 python 很陌生......
我正在尝试从以下格式的 csv 文件将回归系数矩阵读入 python:
0.10 0.15 0.20 0.25 0.30 0.35
a1 -0.0011 0.0008 0.0019 0.0034 0.0067 0.0047-0.0026
a2 0.0134 -0.3042 -0.2531 -0.2138 -1.2345 -0.2380 2.0402
a3 0.0546 0.2708 0.1738 0.0810 0.8451 -0.0034 -1.4961
a4 -0.0226 -0.0052 -0.0021 -0.0024 -0.0023 -0.0745 0.0563
a5 -0.0101 0.0108 0.0153 0.0263 0.0491 0.0327 -0.0691
我需要能够访问该矩阵的特定元素,例如 a['a1','0.10']=-0.0011。我认为字典适合存储这些数据,但发现很难将其变成二维的。
我已经设法将这些数据读取到字典中,以顶行元素作为键,但我不知道如何完成我想要的双重键控。我使用的代码如下:
import csv, sys
reader = csv.DictReader(open(sys.path[0]+"\\DSYHScoeff_98.dat", 'r'), delimiter=' ')
result = {}
for row in reader:
for column, value in row.iteritems():
result.setdefault(column, []).append(value)
您对处理这些数据有什么好的方法建议吗?
最诚挚的问候, 亚当
最佳答案
选择pandas
,它是为这个东西设计的:
>>> import pandas as pd
>>> names = ['0.10', '0.15', '0.20', '0.25', '0.30', '0.35', '0.40']
>>> i = pd.read_csv('test.csv', delim_whitespace=True, names=names)
>>> i
0.10 0.15 0.20 0.25 0.30 0.35 0.40
0 -0.0011 0.0008 0.0019 0.0034 0.0067 0.0047 -0.0026
1 0.0134 -0.3042 -0.2531 -0.2138 -1.2345 -0.2380 2.0402
2 0.0546 0.2708 0.1738 0.0810 0.8451 -0.0034 -1.4961
3 -0.0226 -0.0052 -0.0021 -0.0024 -0.0023 -0.0745 0.0563
4 -0.0101 0.0108 0.0153 0.0263 0.0491 0.0327 -0.0691
>>> i['0.10'][0]
-0.0011000000000000001
关于python - Python 中 CSV 文件的二维字典、列表或数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25547406/