使用Python在CSV文件中删除行

31

我想要做的只是在第三列中有值为'0'的行时删除该行。数据示例如下:

6.5, 5.4, 0, 320
6.5, 5.4, 1, 320

因此,第一行需要被删除,而第二行则保留。

到目前为止,我所拥有的如下所示:

import csv
input = open('first.csv', 'rb')
output = open('first_edit.csv', 'wb')
writer = csv.writer(output)
for row in csv.reader(input):
    if row[2]!=0:
        writer.writerow(row)
input.close()
output.close()

任何帮助都将是极好的。

3个回答

41

您已经非常接近了;目前您正在将row[2]与整数0进行比较,应该使用字符串"0"进行比较。当您从文件中读取数据时,它是一个字符串而不是一个整数,这就是为什么您的整数检查目前失败的原因:

row[2]!="0":

此外,您可以使用 with 关键字,使当前代码更符合Python语言风格,从而减少代码中的行数,并且可以省略 .close 语句:

import csv
with open('first.csv', 'rb') as inp, open('first_edit.csv', 'wb') as out:
    writer = csv.writer(out)
    for row in csv.reader(inp):
        if row[2] != "0":
            writer.writerow(row)

请注意,input是Python内置变量,因此我使用了另一个变量名。


编辑:你的csv文件的行中的值是逗号和空格分隔的;在普通的csv文件中,它们只会用逗号分隔,并且对"0"进行检查就可以了,所以您可以使用strip(row[2]) != 0,或者检查" 0"

更好的解决方案是纠正csv格式,但如果您要坚持使用当前的格式,以下内容将适用于您提供的csv文件格式:

$ cat test.py 
import csv
with open('first.csv', 'rb') as inp, open('first_edit.csv', 'wb') as out:
    writer = csv.writer(out)
    for row in csv.reader(inp):
        if row[2] != " 0":
            writer.writerow(row)
$ cat first.csv 
6.5, 5.4, 0, 320
6.5, 5.4, 1, 320
$ python test.py 
$ cat first_edit.csv 
6.5, 5.4, 1, 320

1
我也尝试过了,但无论是设置为字符串还是整数,它似乎都不起作用。 - Will B
我尝试了你编辑的方法,也尝试了strip()函数,但输出文件仍然有带有“0”值的行! - Will B
我已经运行了几次,结果都一样。 - Will B
1
有没有不必创建和写入额外文件的方法来完成这个任务? - oldboy
1
好的,我在单个文件中找不到任何关于这方面的信息。您能否提供任何有关此事的帖子/信息链接? - oldboy
显示剩余3条评论

3

使用 pandas 强大的库:

该问题的解决方案:

import pandas as pd


df = pd.read_csv(file)
df =  df[df.name != "dog"] 

# df.column_name != whole string from the cell
# now, all the rows with the column: Name and Value: "dog" will be deleted

df.to_csv(file, index=False)

通用的解决方案:

使用此函数:

def remove_specific_row_from_csv(file, column_name, *args):
    '''
    :param file: file to remove the rows from
    :param column_name: The column that determines which row will be 
           deleted (e.g. if Column == Name and row-*args
           contains "Gavri", All rows that contain this word will be deleted)
    :param args: Strings from the rows according to the conditions with 
                 the column
    '''
    row_to_remove = []
    for row_name in args:
        row_to_remove.append(row_name)
    try:
        df = pd.read_csv(file)
        for row in row_to_remove:
            df = df[eval("df.{}".format(column_name)) != row]
        df.to_csv(file, index=False)
    except Exception  as e:
        raise Exception("Error message....")

函数实现:

remove_specific_row_from_csv(file_name, "column_name", "dog_for_example", "cat_for_example")

注意: 在这个函数中,您可以发送无限个字符串单元格,所有这些行将被删除(假设它们存在于发送的单列中)。


1
一行总结:使用类似 Numpy 的过滤方式:df = df[df.my_column != value] - Basj
1
@Basj,你说得对,但请不要忘记当事情被安排为清晰的函数并且有发送无限字符串单元的可能性时所增加的价值。 - Gavriel Cohen

1
你应该使用 if row[2] != "0"。否则它不会检查字符串值是否等于 0。

是的,我之前也試過那個,但它似乎也沒有起作用! - Will B
是的,我正在查看输出文件。 - Will B

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接