如何检查列的某些值并跳过某些行

时间:2021-07-19 09:02:47

标签: python csv

enter image description here

import ctypes
import csv

with open('data.csv') as csv_file:
  reader = csv.reader(csv_file)
  next(reader)

  for row in reader:
     if(int(row[3])>=5):
         print(row)
         mymessage = 'A message'
         title = 'Popup window'
         ctypes.windll.user32.MessageBoxA(0, mymessage, title, 0)
     else:
    continue

我目前有上述 csv 文件和代码。但是,当我执行 print(row) 时,

['string1','00','00','21','00'..]
['string2','00','00','84','00'..]
['string3','00','00','21','00'..]
['string4','00','00','21','00'..]
               .
               .
               .
['string7','00','00','21','00'..]
['string8','00','00','84','00'..]
['string9','00','00','15','00'..]
['string10','00','00','84','00'..]
['       ','precision','recall','f1-score','support'..]

它像上面一样打印。

with open('data.csv') as csv_file:
  reader = csv.reader(csv_file)
  next(reader)

  for row in reader[1:-8]:
         print(row)
         if(int(row[3])>=5):
              mymessage = 'A message'
              title = 'Popup window'
              ctypes.windll.user32.MessageBoxA(0, mymessage, title, 0)
         else:
            continue

所以为了忽略图片的红色部分,我想我可以通过上面的代码跳过最后八行。但是有个问题。

我使用它的两个问题是:

  1. 我不知道总行数,因为
  2. 每次写入 CSV 文件时,strings1 到 n 的数量都会发生变化。

在我尝试时,我想在检查特定列中的每个值是否大于 5 时删除下面不必要的行。

2 个答案:

答案 0 :(得分:1)

这会在将 csv 导入 python 之前为您提供行数。

lines = sum(1 for line in open('data.csv'))  # gives you the total number of lines without loading csv

然后你可以在没有最后 8 行的情况下导入它(就像下面的熊猫示例)

import pandas as pd

data = pd.read_csv('data.csv', delimiter=';', decimal='.', header=0, skipfooter=8)  # loads the csv without last 8 rows

或者您使用没有最后 8 行的代码加载它。

连接你的代码应该是:

lines = sum(1 for line in open('data.csv'))  # gives you the total number of lines without loading csv
with open('data.csv') as csv_file:

  reader = csv.reader(csv_file)
  next(reader)

  for row in range(lines-8):  # using the number of lines here. It doesn't even load the last 8 lines
         print(row)
         if(int(row[3])>=5):
              mymessage = 'A message'
              title = 'Popup window'
              ctypes.windll.user32.MessageBoxA(0, mymessage, title, 0)
         else:
            continue

答案 1 :(得分:0)

我终于得到了答案。我们可以让csv阅读器通过Object reference not set to an instance of an object.读取一定范围的行。

itertools.islice

所以我使用了这个代码。

from itertools import islice

with open('data.csv') as csv_file:
   reader = csv.reader(csv_file)
   #next(reader) We don't need this anymore beacause we read only certain rows.

   for row in islice(reader, 0, 10): #reads the row from 1 to 11
       print(row)
     if(int(row[3])>=5):
          mymessage = 'A message'
          title = 'Popup window'
          ctypes.windll.user32.MessageBoxA(0, mymessage, title, 0)
     else:
        continue

如果您的 csv 总行数不固定,您可以像这样使用上面的代码。