You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 a float so 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.01 to 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-except block 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 20:33:10