如何使用python识别(但不修复)csv文件中的空值或重复值?
我对编程非常陌生,我不知道如何使用简单的python程序简单地识别csv文件中的重复记录和空值。我不想修复它们,我只想识别它们。我以前也问过类似的问题,人们给了我关于熊猫模块的答案,但我现在恐怕这比我高了一点,所以如果人们给我不涉及熊猫的答案,我将不胜感激,因为这不会真正帮助我! 这是代码,很抱歉,如果它让你想哭它的质量差和(希望不是)无关的性质,但我真的卡住了,所以这是我能做的最好的自己如何使用python识别(但不修复)csv文件中的空值或重复值?,python,python-3.x,csv,file,Python,Python 3.x,Csv,File,我对编程非常陌生,我不知道如何使用简单的python程序简单地识别csv文件中的重复记录和空值。我不想修复它们,我只想识别它们。我以前也问过类似的问题,人们给了我关于熊猫模块的答案,但我现在恐怕这比我高了一点,所以如果人们给我不涉及熊猫的答案,我将不胜感激,因为这不会真正帮助我! 这是代码,很抱歉,如果它让你想哭它的质量差和(希望不是)无关的性质,但我真的卡住了,所以这是我能做的最好的自己 with open('testdata1.csv', 'r') as csv_file: csv_read
with open('testdata1.csv', 'r') as csv_file:
csv_reader = csv.reader(csv_file)
for row in csv_reader:
if not row[0]:
continue
虽然不多,但我迷路了,需要一些帮助。
非常感谢比如说,你制作了2d数组,矩阵,每个销售包含一个值-0或浮点或整数
array = [[0,0,0],[0,1,0],[1,2,3],[1,2,3]]
for i in range(0,len(array)):
for j in range(1,len(array[i])):
if array[i][j] == array[i][j-1]:
#element is duplicated
print('duplicate',i,j)
elif array[i][j] == 0:
print('null',i,j)
希望这对你有帮助。对于更高级的技术,最好使用pandas。只是澄清一下,下面的代码不一定是实现这一点的最佳方法,而且有多种方法。然而,由于您似乎在python职业生涯的早期,我将尝试解释这些概念 您已经在代码中开始了如何执行此操作。该行:
if not row[0]:
正在检查行中的第一个元素的计算结果是否为True
或False
。在这种情况下,由于not
,值True
将不会传递,而值False
将传递。试着退房
您的变量行
是一个可以迭代的列表。我将对您的代码稍作修改,以便在循环行时给出索引:
# 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()
将为csv中的不同案例提供什么类型(项目)
- 您可以在
语句中使用上述内容,例如if
if type(1)==int:
- 空值很可能由空字符串
”表示,因此如果item==”:“
检查其他列表中是否已经有内容,例如:
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)
我知道你在你的问题中提到了这一点,但熊猫会让这更容易。我认为您首先尝试理解基本原理是正确的,但在熊猫中,这将是一个简单的:
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()]
我认为学习熊猫比分析这个层次的数据更容易