根据特定的列值python删除csv中的行 [英] delete rows in csv based on specific column value python

查看:77
本文介绍了根据特定的列值python删除csv中的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个大型的csv,具有以下标头列 id type state location 学生人数

I have a large csv with the following header columns id, type, state, location, number of students

和以下值:

124, preschool, Pennsylvania, Pittsburgh, 1242
421, secondary school, Ohio, Cleveland, 1244
213, primary school, California, Los Angeles, 3213
155, secondary school, Pennsylvania, Pittsburgh, 2141
etc...

该文件未排序,我想要一个新的csv文件,其中包含学生人数超过2000名的所有学校.

The file is not ordered and I want a new csv file that contains all the schools with the number of students above 2000.

我找到的答案与有序的csv文件有关,或者是在特定的行数后将它们拆分.

The answers that I found were regarding to ordered csv files, or splitting them after a specific number of rows.

推荐答案

以下是使用 csv 模块的解决方案:

Here's a solution using csv module:

import csv

with open('fin.csv', 'r') as fin, open('fout.csv', 'w', newline='') as fout:

    # define reader and writer objects
    reader = csv.reader(fin, skipinitialspace=True)
    writer = csv.writer(fout, delimiter=',')

    # write headers
    writer.writerow(next(reader))

    # iterate and write rows based on condition
    for i in reader:
        if int(i[-1]) > 2000:
            writer.writerow(i)

结果:

id,type,state,location,number of students
213,primary school,California,Los Angeles,3213
155,secondary school,Pennsylvania,Pittsburgh,2141

这篇关于根据特定的列值python删除csv中的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆