首页 > 解决方案 > 您如何使用 python 识别(但不修复)csv 文件中的空值或重复值?

问题描述

我对编程很陌生,我不确定如何使用简单的 python 程序简单地识别 csv 文件中的重复记录和空值。我不想修复它们,我只想识别它们。我之前问过类似的问题,人们给了我涉及 pandas 模块的答案,但我恐怕现在有点超出我的要求,所以如果人们能给我不涉及 pandas 的答案,我将不胜感激,因为它不会t真的帮助我!这是代码,对不起,如果它让你想哭它的质量差和(希望不是)无关紧要的性质,但我真的被困住了,所以这是我自己能做的最好的事情。

with open('testdata1.csv', 'r') as csv_file:
csv_reader = csv.reader(csv_file)
for row in csv_reader:
    if not row[0]:
         continue

这并不多,但我迷路了,需要一些帮助。非常感谢

标签: pythonpython-3.xcsvfile

解决方案


只是澄清一下,下面的代码不一定是执行此操作的最佳方法,并且有多种方法。但是,由于您似乎还处于 Python 职业生涯的早期,我将尝试解释这些概念。

您已经开始在代码中执行此操作了。该行:

if not row[0]:

正在检查行中的第一个元素的计算结果是否为Trueor False。在这种情况下,由于not, 的值True不会通过而将的值False。尝试查看此页面,特别是 4.4 和 4.10

您的变量row是一个可以迭代的列表。我将对您的代码稍作修改,只是为了在您遍历行时提供索引:

# Using enumerate() returns the index, too.
# So the first row will have i=0, the second i=1 etc. 
for i, row in enumerate(csv_reader):
    # Now you can loop through each item in the row itself
    for j, item in enumerate(row):
        # Now for your logic to check if it's null
        if not item:
            # This will print the row number, the column number, and the item
            # should it not pass the check.
            print(f"Item in row {i + 1} and column {j + 1} is: {item}")

现在,如果您按照上面的链接,您将在第 4.10 节中看到值0也会导致打印,因此您可能需要根据需要修改此逻辑。我鼓励您对此进行迭代并找到适合您的逻辑,但还有一些要点是:

  • 您可以使用 . 检查变量的类型type()。检查type(item)您的 csv 中不同情况的情况。
  • if您可以在语句中使用上述内容,例如if type(1) == int:
  • Null 可能由空字符串表示"",因此您可以检查if item == "":

检查重复项会有点困难,您可能必须记录您已经看到的内容,但您可以使用 来检查是否已经在另一个列表中in,例如:

1 in [1, 2, 3]
>>> True

4 in [1, 2, 3]
>>> False

# You can check lists, too
[1, 2] in [[1, 2], [2, 3], [3, 4]]
>>> True

[1, 4] in [[1, 2], [2, 3], [3, 4]]
>>> False
 

因此,您可能希望跟踪您在新列表中看到的每一行,并为每一行检查它是否已经在该列表中。跟踪重复行的东西可能是:

seen_rows = []
duplicate_rows = []
for row in csv_reader:
    # If the row is already in seen_rows, add it to duplicate_rows
    if row in seen_rows:
        duplicate_rows.append(row)
    # If not, add it to seen_rows so you can check future rows against it.
    else:
        seen_rows.append(row)

我知道你已经在你的问题中解决了这个问题,但是 pandas 会让这更容易。我认为您首先尝试了解基础知识是正确的,但是在熊猫中这很简单:

df = pandas.read_csv('testdata1.csv')
# This would select the rows that have any null values in them.
null_rows = df[df.isnull().any(axis=1)]

# This would select rows that are duplicates
duplicate_rows = df[df.duplicated()]

推荐阅读