Python中从CSV文件创建二维字典、列表或数组
我刚开始接触Python...
我想从一个CSV文件中读取一个回归系数矩阵,文件格式如下:
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)
你有什么好的方法来处理这些数据吗?
最好的祝福,
亚当
4 个回答
0
老实说,我会手动来做这件事。
header,data = None,dict()
with open("filename.csv") as f:
for line in f:
if header is None:
header = line.split()
continue
l = line.split()
for i in xrange(len(l)-1):
data[l[0],header[i]] = l[i+1]
在我做了tobias_k在评论中提到的调整后,这个方法就能正常工作了。
0
我会在文件开头加上类似“ax”的东西:
ax 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
[...]
然后稍微修改一下你的代码:
result = {}
for row in reader:
x = row.pop(reader.fieldnames[0])
for column, value in row.iteritems():
if column and value:
y = float(column)
result[x,y] = float(value)
这样应该就能正常工作了:
>>> result['a3',0.15]
0.2708
0
首先,你需要给第一列添加一个标签:
# ▼▼▼
row 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
# [...]
接下来,这只是一个获取“行列”中行索引的问题。把它放在一个函数里:
def cell(arr,row,col):
try:
return result[col][result['row'].index(row)]
except KeyError:
return "N/A"
根据你的输入文件和你的代码:
#
# insert your code here
#
from pprint import pprint
pprint(result)
def cell(arr,row,col):
try:
return result[col][result['row'].index(row)]
except KeyError:
return "N/A"
pprint(cell(result, 'a1', '0.10'))
pprint(cell(result, 'a1', '0.14'))
生成的结果是:
{None: [[''], [''], [''], ['']],
'': ['', '2.0402', '-1.4961', '0.0563', '-0.0691'],
'0.10': ['-0.0011', '0.0134', '0.0546', '-0.0226', '-0.0101'],
'0.15': ['0.0008', '-0.3042', '0.2708', '-0.0052', '0.0108'],
'0.20': ['0.0019', '-0.2531', '0.1738', '-0.0021', '0.0153'],
'0.25': ['0.0034', '-0.2138', '0.0810', '-0.0024', '0.0263'],
'0.30': ['0.0067', '-1.2345', '0.8451', '-0.0023', '0.0491'],
'0.35': ['0.0047-0.0026', '-0.2380', '-0.0034', '-0.0745', '0.0327'],
'row': ['a1', 'a2', 'a3', 'a4', 'a5']}
'-0.0011'
'N/A'
(请注意,你的输入数据文件可能格式不太正确;从pprint
打印出的字典来看,这一点很明显——具体细节可以参考你提问时的评论)
3
可以使用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