为了账号安全,请及时绑定邮箱和手机立即绑定

在python中,如何删除特定列为空白的整行?

在python中,如何删除特定列为空白的整行?

莫回无 2021-10-12 16:43:09
我试图弄清楚如何使下面的代码排除 row[9] 具有空白条目的任何实例。当前,csv 文件为每一行输出,这会导致行中的“爸爸”条目为空白。我希望输出 csv 文件不包含“爸爸”列(行 [9])为空的任何行...任何帮助是极大的赞赏!def guardiansfather():with open('hallpass_raw.csv') as csv_file:    csv_reader = csv.reader(csv_file, delimiter=',')    with open('outputfiles/guardians_father.csv', mode='w', newline='') as output_file:        write = csv.writer(output_file, delimiter=',', quoting=csv.QUOTE_MINIMAL)        for row in csv_reader:            a = row[0]            b = row[1]            c = row[2]            studentnumber = row[3]            firstname = row[4]            middlename = row[5]            lastname = row[6]            teacher = row[7]            idnumber = row[8]            father = row[9]            mother = row[10]            guardianemail = row[11]            phone = row[12]            fatheremail = row[13]            motheremail = row[14]            guardianphone = row[15]            schoolname = 'NAME OF SCHOOL'            relationship = 'Father'            father_first = father.split(sep=','[0])            father_last = father.split(sep=', '[1])            write.writerow([schoolname, studentnumber, father_first, father_last, relationship, phone, fatheremail])
查看完整描述

2 回答

?
慕妹3242003

TA贡献1824条经验 获得超6个赞

使用if声明


def guardiansfather():

    with open('hallpass_raw.csv') as csv_file:

        csv_reader = csv.reader(csv_file, delimiter=',')

        with open('outputfiles/guardians_father.csv', mode='w', newline='') as output_file:

            write = csv.writer(output_file, delimiter=',', quoting=csv.QUOTE_MINIMAL)

            for row in csv_reader:

                a = row[0]

                b = row[1]

                c = row[2]

                studentnumber = row[3]

                firstname = row[4]

                middlename = row[5]

                lastname = row[6]

                teacher = row[7]

                idnumber = row[8]

                father = row[9]


                # Skip rows with empty father

                if father.strip() == '':

                    continue


                mother = row[10]

                guardianemail = row[11]

                phone = row[12]

                fatheremail = row[13]

                motheremail = row[14]

                guardianphone = row[15]

                schoolname = 'NAME OF SCHOOL'

                relationship = 'Father'

                father_first = father.split(sep=','[0])

                father_last = father.split(sep=', '[1])


                write.writerow([schoolname, studentnumber, father_first, father_last, relationship, phone, fatheremail])


查看完整回答
反对 回复 2021-10-12
  • 2 回答
  • 0 关注
  • 286 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信