英文:
How to assign objects read from csv file with pandas to some Class?
问题
我有一个示例类:
class Automobile:
def __init__(self, name, lastname, country, year, model, price):
我想要读取一个类似表格的 CSV 文件,其中列与 Automobile 类的属性相同。我想要从那个 CSV 文件创建一个 Automobile 类对象的列表。有人可以帮忙吗?
英文:
I have one class for example:
class Automobile:
def __init__(self, name, lastname, country, year, model, price):
and I want to read csv file which looks like table with columns the same as the attributes of class Automobile. I want to create a list of objects of Automobile class from that csv file. Could anyone help?
答案1
得分: 0
如果您的CSV文件有一个标题行,其中的标题与参数的名称匹配,您可以使用**
和csv.DictReader
基本上免费获得此功能。
test.csv
a,b
1,2
3,4
import csv
class A:
def __init__(self, a, b):
self.a = a
self.b = b
a_objects = []
with open('test.csv') as f:
reader = csv.DictReader(f)
for line in reader:
a_objects.append(A(**line))
如果CSV文件没有明确的标题行,那么可以将它们临时传递给DictReader
:
reader = csv.DictReader(f, fieldnames=['a', 'b'])
请记住,只要代码或CSV文件发生更改,此方法就会失败,因此您需要一些错误处理(或者至少使用**kwrags
来保护类的__init__
免受未知列的影响)。
英文:
If your CSV file has a header row with the headers matching the parameters' names, you can get this functionality for basically free with **
and csv.DictReader
.
test.csv
a,b
1,2
3,4
import csv
class A:
def __init__(self, a, b):
self.a = a
self.b = b
a_objects = []
with open('test.csv') as f:
reader = csv.DictReader(f)
for line in reader:
a_objects.append(A(**line))
If the CSV file does not have explicit headers then it is possible to pass them ad-hoc to DictReader
:
reader = csv.DictReader(f, fieldnames=['a', 'b'])
Keep in mind this is will fail as soon as either the code or the CSV file changes so you will need some error handling (or at least protect the class's __init__
against unknown columns with **kwrags
).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论