问题/上下文: 我正在尝试编写一个代码,该代码将读取指定文件夹中的每个 CSV 文件,查找列索引 [1] 中第二次连续出现的零,并在找到时显示列索引 [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]列中与第[1]列中第二个连续零位于同一行的值。 实际结果:每行返回“在第 2 列中未找到第二个零。”
您可以设置
col0, col1 = df.columns[:2]
,然后使用以下一行,该行使用 col1
中的值的累积计数。
col1_value = df.loc[(df.groupby(col1).cumcount() == 1) & (df.col1 == 0), [col0]].values[0][0]
对于以下数据框:
>>> df
col0 col1
0 1 1
1 2 0
2 3 0 # second consecutive occurrence of 0
3 4 2
4 5 2
5 6 0
6 7 0
7 8 0
8 9 2
9 10 2
col1_value = 3
对应于第二次连续出现 0。