Python初学者求助:CSV数据过滤if语句失效问题
Fixing Your CSV Filtering Issue
Hey there! Let's get your CSV filtering working properly. The main issue with your current code is that values read from CSV files are strings by default, so comparing row[8] >= 1 isn't doing what you think it is—you're comparing a string to a number, which uses ASCII character order instead of numeric value. Plus, your condition is checking for values >=1, but you mentioned you want to keep rows where column 8 is 0.01 or higher.
Here's the corrected code, with explanations:
import csv # Use a `with` statement to handle the file safely (it auto-closes when done) with open('data.csv', 'r') as m: csv_m = csv.reader(m) # Optional: If your CSV has a header row, uncomment the line below to skip it # next(csv_m) for row in csv_m: try: # Convert column 8 from string to float for numeric comparison column8 = float(row[8]) # Check if the value is 0.01 or higher if column8 >= 0.01: print(row[0], row[1], row[8], row[18]) except ValueError: # Handle cases where column 8 isn't a number (avoids crashing your script) print(f"Skipping invalid row - column 8 isn't a number: {row}")
Key Fixes & Notes:
- Data Type Conversion: We convert
row[8]to afloatso we can do proper numeric comparisons. Without this, strings like"0.5"would be treated as text, not a number. - Corrected Condition: Changed the check to
column8 >= 0.01to match your requirement of keeping values 0.01 and above. - Safe File Handling: Using
with open(...)ensures the file is closed automatically, even if your script hits an error. - Error Handling: The
try-exceptblock catches cases where column 8 might have non-numeric values (like empty cells or text), so your script doesn't crash unexpectedly.
If you run this, it should only print rows where column 8 has a value of 0.01 or higher—exactly what you want!
内容的提问来源于stack exchange,提问作者Steve Curtis
相关产品推荐
相关产品推荐

