如何将csv文件的行转换为对象列表?

时间:2019-07-10 17:27:01

标签: python class dictionary object

我正在处理患者数据。我将患者数据存储在CSV文件中。每行是一个新患者,有数百名患者。我想以清单的发生率来访问患者。例如,我的患者列表的索引0将输出具有以下属性的患者对象:

{首先:“撒迦利亚”, 最后:“ Siyaji”, 年龄:21}

,依此类推。以下是我正在编写的代码,尽管我看不到如何在没有手动初始化每个对象的情况下生成许多对象。考虑到有数百名患者,这是非常不切实际的。

import ASD as asd

class Patient:
    mrn = 0
    first = '' 
    last = '' 
    gender = 0
    smoker = 0
    bmi = 0
    asa = 0 
    cci = 0
    dob = '' 
    dos = '' 
    age = 0

    def setData(self, mrn, first, last, gender, smoker, bmi, asa, cci, dob, dos, age):
        self.mrn = mrn
        self.first = first
        self.last = last
        self.gender = gender
        self.smoker = smoker
        self.bmi = bmi
        self.asa = asa
        self.cci = cci
        self.dob = dob
        self.dos = dos
        self.age = age

    def showData(self):
        print("MRN\t:",self.mrn)
        print("First\t:", self.first)
        print("Last\t:", self.last)
        print("Gender\t:", self.gender)
        print("Smoker\t:", self.smoker)
        print("BMI\t:",self.bmi)
        print("ASA\t:", self.asa)
        print("CCI\t:", self.cci)
        print("DOB\t:", self.dob)
        print("DOS\t:", self.dos)
        print("Age\t:", self.age)

def main():

    p1 = Patient()
    p1.setData(asd.file1['MRN'][0],
               asd.file1['First'][0],
               asd.file1['Last'][0],
               asd.file1['Female'][0],
               asd.file1['Smoker'][0],
               asd.file1['BMI'][0],
               asd.file1['ASA'][0],
               asd.file1['CCI'][0],
               asd.file1['DOB'][0],
               asd.file1['DOS'][0],
               asd.file1['Age'][0])
    p1.showData()

if __name__ == '__main__':
    main()

2 个答案:

答案 0 :(得分:0)

您只需导入熊猫并读取CSV文件并访问患者信息。

import pandas as pd
patients = pd.read_csv("patients.csv")

# To access information
patients.loc[0] #or patients.iloc[0]

答案 1 :(得分:0)

csv模块支持从csv文件读取。如果您想进行复杂的数据插值,那么当然还有熊猫。假设它是一个简单的操作,应该看起来像这样,

import csv

with open(filename, 'r') as stream:
  reader = csv.DictReader(stream)
  count == 0
  for row in reader:
    if count != 0 # skip the header, or do something here
    p = Patient(row["mrn"], row["first"], row["last"], row["gender"], row["smoker"], row["bmi"], row["asa"], row["cci"], row["dob"], row["dos"], row["age"])
    print(p)
    count += 1

我还看到您的患者定义类不遵循惯用的python。可以通过以下方式将其重写为更具Python风格的

class Patient:
   def __init___(self, mrn=None, first=None, last=None, gender=None, smoker=None, bmi=None, asa=None, cci=None, dob=None, dos=None, age=None)
     self.mrn = mrn
     self.first = first
     self.last = last
     self.gender = gender
     self.smoker = smoker
     self.bmi = bmi
     self.asa = asa
     self.cci = cci
     self.dob = dob
     self.dos = dos
     self.age = age
def __repr__(self):
    return '''MRN: {}
            First: {}
            ...
            ASA: {}'''.format(self.mrn, self.first,....,self.asa)

由于构造函数具有许多字段,所以最大的优点之一就是您可以使用关键字参数实例化您的类,并降低将某些字段与其他值混淆的风险。