问题/上下文:我正在尝试编写一个代码来读取指定文件夹中的每个CSV文件,在列索引中查找第二次连续出现的零,并显示列索引[0中的相应值] 当发现时。以下是我到目前为止所拥有的,但它不起作用。它只是表示不存在具有两个连续零的列。但是,当我打开各个文件时,我可以清楚地看到有些列带有两个连续的零。 我之前问过这个问题并得到了有效的结果,直到我替换了我自己的数据框。也许是因为我自己的数据框既包含数字又包含单词?
数据框:
当前代码:
import os
import pandas as pd
folder_path = "/content/drive/session 1 & 2"
def find_column1_value_for_second_zero(file_path):
try:
df = pd.read_csv(file_path)
consecutive_zeros = 0
column1_value = None
for _, row in df.iterrows():
if row.iloc[1] == 0:
consecutive_zeros += 1
if consecutive_zeros == 2:
column1_value = row.iloc[0]
break
else:
consecutive_zeros = 0
return column1_value
except Exception as e:
print(f"Error reading file '{file_path}': {str(e)}")
return None
for filename in os.listdir(folder_path):
if filename.endswith(".csv"): # Assuming your files are CSV format
file_path = os.path.join(folder_path, filename)
column1_value = find_column1_value_for_second_zero(file_path)
if column1_value is not None:
print(f"In file '{filename}', the value in column 1 for the second zero in column 2 is: {column1_value}")
else:
print(f"In file '{filename}', no second zero in column 2 was found.")
预期结果:获取与第中第二个连续零位于同一行的第[0]列中的值。在上面的数据框中,它应该返回“11”。
实际结果:每行返回“在第 2 列中未找到第二个零。”
没有您的 csv 数据我们如何测试?
又一个基于我认为你的 csv 的工作解决方案。
from pathlib import Path
import csv
folder_path = '.'
def find_column1_value_for_second_zero(file_path):
with open(file_path, newline='') as f:
consec = 0
for row in csv.reader(f):
try: x, y = row[0], float(row[1])
except ValueError: continue
consec = 0 if y != 0 else consec + 1
if consec == 2: return x
if __name__ == '__main__':
for filename in Path(folder_path).glob('*csv'):
column1_value = find_column1_value_for_second_zero(filename.resolve())
if column1_value:
print(f"In file '{filename}', the value in column 1 for the second zero in column 2 is: {column1_value}")
else:
print(f"In file '{filename}', no second zero in column 2 was found.")