将从CSV文件中读取的对象分配给某个类的方法如何?

huangapple go评论65阅读模式
英文:

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).

huangapple
  • 本文由 发表于 2023年5月14日 23:38:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/76248327.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定