Python-如何使用列标题从CSV数据文件创建字典 [英] Python - How to Create Dictionary from CSV data file using column headings
本文介绍了Python-如何使用列标题从CSV数据文件创建字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试创建一个函数,该函数接受.csv数据文件的名称和表示该文件中列标题的字符串列表,并返回一个dict对象,每个键为列标题,而对应的值为numpy数据文件该列中的值的数组.
I am trying to create a function that accepts the name of a .csv data file and a list of strings representing column headings in that file and return a dict object with each key being a column heading and the corresponding value being a numpy array of the values in that column of the data file.
我现在的代码:
def columndata(filename, columns):
d = dict()
for col in columns:
with open(filename) as filein:
reader = csv.reader(filein)
for row in reader:
if col in row:
d.append(row)
return d
示例CSV如下:
test1,test2
3,2
1,5
6,47
1,4
columns文件如下:
The columns file looks like:
cols = ['test1', 'test2']
最终结果应该是这样的字典:
The end result should be a dictionary like this:
{'test1':[3,1,6,1], 'test2':[2, 5, 4, 4]}
推荐答案
您可以使用 DictReader ,它将CSV数据解析为字典:
You can use a DictReader which parse the CSV data into a dict:
import csv
from collections import defaultdict
def parse_csv_by_field(filename, fieldnames):
d = defaultdict(list)
with open(filename, newline='') as csvfile:
reader = csv.DictReader(csvfile, fieldnames)
next(reader) # remove header
for row in reader:
for field in fieldnames:
d[field].append(float(row[field])) # thanks to Paulo!
return dict(d)
print(parse_csv_by_field('a.csv', fieldnames=['cattle', 'cost']))
这篇关于Python-如何使用列标题从CSV数据文件创建字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文