簡體   English   中英

使用 Python 刪除 CSV 文件中的行

[英]Deleting rows with Python in a CSV file

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

任何幫助都會很棒

你很親近; 當前,您將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

你應該有if row[2] != "0" 否則它不會檢查字符串值是否等於 0。

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

注意:在這個函數中,你可以發送無限的字符串單元格,所有這些行都將被刪除(假設它們存在於發送的單列中)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM