【问题标题】:Deleting rows with Python in a CSV file在 CSV 文件中使用 Python 删除行
【发布时间】:2015-06-25 21:11:01
【问题描述】:

我想做的就是删除第三列中值为“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()

任何帮助都会很棒

【问题讨论】:

    标签: python csv


    【解决方案1】:

    使用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")
    

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

    【讨论】:

    • 一行总结:使用Numpy风格的过滤:df = df[df.my_column != value]
    • @Basj,你是对的,但是当事情被安排成一个清晰的功能和发送无限的字符串单元的可能性时,请不要忘记附加值
    【解决方案2】:

    你们很亲近;目前您将row[2] 与整数0 进行比较,与字符串"0" 进行比较。当您从文件中读取数据时,它是一个字符串而不是整数,这就是您的整数检查当前失败的原因:

    row[2]!="0":
    

    此外,您可以使用 with 关键字使当前代码稍微更 Pythonic,从而减少代码中的行数,并且您可以省略 .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
    

    【讨论】:

    • 我也试过了,但是不管设置为字符串还是整数,它似乎都不起作用
    • 我试过你编辑它的方式,我也试过做一个strip(),但输出文件仍然有'0'值的行!
    • 我运行了几次,结果还是一样。
    • @WillB 我不确定你在运行什么,我已经发布了我正在使用的输入和代码。也许,您应该在 for 循环中使用 pdb.set_trace() 语句来确定它为什么不起作用。
    • 我将我的 csv 转换为 .txt 以查看它是否将其读取为“00.0000”,这是使其工作的唯一方法。感谢您帮我解决问题!
    【解决方案3】:

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

    【讨论】:

    • 是的,我也尝试过,但它似乎也不起作用!
    • 是的,我正在查看输出文件
    猜你喜欢
    • 1970-01-01
    • 2020-06-19
    • 2019-11-17
    • 2016-05-12
    • 1970-01-01
    • 1970-01-01
    • 2021-08-20
    • 1970-01-01
    • 2020-05-15
    相关资源
    最近更新 更多