如何用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'tocsv.reader()instead of the opened file objectf - The nested
whileandforloop 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:
(target_col == 1)converts all values in the column to booleans (True for 1, False otherwise)rolling(window=10)creates a sliding window of 10 rows.sum()counts how many True values (i.e., 1s) are in each window.eq(10)checks if any window has exactly 10 True values.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

