如何用Pandas读取CSV文件并生成自定义Automobile类的对象列表?
从CSV生成Automobile对象列表的实现方法
1. 确认Automobile类的定义
先确保类的构造方法参数和CSV列名完全匹配,示例代码:
class Automobile: def __init__(self, name, lastname, country, year, model, price): self.name = name self.lastname = lastname self.country = country self.year = year self.model = model self.price = price # 可选:添加这个方法让对象打印更直观 def __repr__(self): return f"Automobile(name='{self.name}', lastname='{self.lastname}', country='{self.country}', year={self.year}, model='{self.model}', price={self.price})"
2. 用Python内置csv模块读取文件并生成对象
利用csv.DictReader可以直接把每行数据转成字典,再通过**语法传递给类的构造方法,代码如下:
import csv def build_automobile_list(csv_path): autos = [] with open(csv_path, 'r', encoding='utf-8') as f: # DictReader会自动用第一行作为键名 reader = csv.DictReader(f) for row in reader: # 注意:year和price是数值类型,需要做类型转换 try: row['year'] = int(row['year']) row['price'] = float(row['price']) except ValueError as e: print(f"Skipping invalid row {row}: {e}") continue # 把字典键值对作为参数传入构造方法 auto = Automobile(**row) autos.append(auto) return autos # 调用示例 my_autos = build_automobile_list('your_file.csv') # 验证结果 print(my_autos[0])
关键注意点
- 必须保证CSV的列名与Automobile类__init__的参数完全一致(大小写也要对应),否则会抛出参数不匹配的错误
- 如果CSV文件用了非utf-8编码(比如gbk),要修改
open方法里的encoding参数 - 如果存在空值或格式错误的数据,要添加异常处理避免程序崩溃,比如上面的try-except块
内容的提问来源于stack exchange,提问作者mungos032
相关产品推荐
相关产品推荐

