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

如何用Python读取CSV特定列并检测是否存在连续10个1?

Hey there! Let's sort out your problem and get that code working properly.

First, let's break down the error you're seeing:

AttributeError: '_csv.reader' object has no attribute 'index_col'

This happens because index_col is not a method of Python's built-in csv.reader object — that's a property used by the pandas library when working with DataFrames. Your code is using the native csv module, so calling that method will throw an error right away.

Plus, there are a couple other issues in your original code:

  • You passed the filename string 'file.csv' to csv.reader() instead of the opened file object f
  • The nested while and for loop logic is unnecessary (it would re-read the file 10 times) and doesn't actually track consecutive values correctly.

Let's fix this with two solid solutions — one using pandas (super clean and efficient) and another using only Python's native csv module if you don't want to install extra libraries.

Solution 1: Use Pandas (Simpler & Faster)

First, make sure pandas is installed:

pip install pandas

Then use this code to check for 10 consecutive 1s in your target column:

import pandas as pd

# Load the CSV and grab your target column (replace 'Output' with your actual column name)
df = pd.read_csv('file.csv')
target_col = df['Output']

# Check if there's any window of 10 consecutive 1s
has_consecutive_ones = (target_col == 1).rolling(window=10).sum().eq(10).any()

if has_consecutive_ones:
    print("Found 10 consecutive 1s!")
else:
    print("No 10 consecutive 1s found.")

Here's what this code does:

  1. (target_col == 1) converts all values in the column to booleans (True for 1, False otherwise)
  2. rolling(window=10) creates a sliding window of 10 rows
  3. .sum() counts how many True values (i.e., 1s) are in each window
  4. .eq(10) checks if any window has exactly 10 True values
  5. .any() returns True if at least one window meets the condition

Solution 2: Use Python's Native CSV Module

If you prefer not to use pandas, this native implementation will work too:

import csv

TARGET_COLUMN = 'Output'  # Replace with your actual column name
consecutive_ones = 0
found = False

with open('file.csv', 'r') as f:
    reader = csv.DictReader(f)  # Lets us access columns by name
    
    # First make sure the target column exists
    if TARGET_COLUMN not in reader.fieldnames:
        print(f"Error: Column '{TARGET_COLUMN}' not found in the CSV.")
    else:
        for row in reader:
            # Convert the value to integer (CSV reads everything as strings)
            try:
                value = int(row[TARGET_COLUMN])
            except ValueError:
                # If the value isn't a number, reset the count
                consecutive_ones = 0
                continue
            
            if value == 1:
                consecutive_ones += 1
                # Check if we've hit 10 in a row
                if consecutive_ones >= 10:
                    found = True
                    break
            else:
                # Reset count if we hit a non-1 value
                consecutive_ones = 0

if found:
    print("Found 10 consecutive 1s!")
else:
    print("No 10 consecutive 1s found.")

This code tracks a running count of consecutive 1s as it reads each row. If it hits a non-1 value, it resets the count. As soon as the count hits 10, it stops checking and reports success.

内容的提问来源于stack exchange,提问作者Rabia Rauf

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:31:59