如果在 pandas 中遍历多个文件时满足条件,如何跳过 for 循环迭代?
How do I skip a for loop iteration if a condition is met when iterating through multiple files in pandas?
我首先使用 os 和 glob 创建一个 CSV 列表,然后使用一个简单的 for 循环遍历应用我的代码的路径中的所有文件。
path = r'my path'
os.chdir(path)
FileList = glob.glob('*.csv')
for fname in FileList:
Session = pd.read_csv(fname, header = 3, usecols = [0, 1])
Session = Session[Session['System'].str.contains('Day', na=False)]
Session = Session['No System Name'].tolist()
CRFs = sum(["CRF" in x for x in Session])
...
df.to_csv(path + 'test_' + fname , index = 0)
如果 Session 的长度等于 CRF,有没有办法让循环跳过一个文件,循环将停止并从 FileList 中的下一个文件重新开始?
我尝试过使用 break 和 continue 这样做,但都没有做任何事情:
for fname in FileList:
Session = pd.read_csv(fname, header = 3, usecols = [0, 1])
Session = Session[Session['System'].str.contains('Day', na=False)]
Session = Session['No System Name'].tolist()
CRFs = sum(["CRF" in x for x in Session])
if CRFs == len(Session) is True:
continue(or break)
...
df.to_csv(path + 'test_' + fname , index = 0)
非常感谢!
当某些情况发生时,您可以中断主循环,请查看有关此主题的official documentation。
是的!我相信 continue 语句正是您要找的。
执行时,continue
语句将导致当前循环迭代的执行结束,并开始下一次迭代。
来自 python 文档的示例:
>>> for num in range(2, 10):
... if num % 2 == 0:
... print("Found an even number", num)
... continue
... print("Found an odd number", num)
...
Found an even number 2
Found an odd number 3
Found an even number 4
Found an odd number 5
Found an even number 6
Found an odd number 7
Found an even number 8
Found an odd number 9
而不是您的代码中的以下内容:
if CRFs == len(Session) is True:
continue
就这样:
if CRFs == len(Session):
continue
我首先使用 os 和 glob 创建一个 CSV 列表,然后使用一个简单的 for 循环遍历应用我的代码的路径中的所有文件。
path = r'my path'
os.chdir(path)
FileList = glob.glob('*.csv')
for fname in FileList:
Session = pd.read_csv(fname, header = 3, usecols = [0, 1])
Session = Session[Session['System'].str.contains('Day', na=False)]
Session = Session['No System Name'].tolist()
CRFs = sum(["CRF" in x for x in Session])
...
df.to_csv(path + 'test_' + fname , index = 0)
如果 Session 的长度等于 CRF,有没有办法让循环跳过一个文件,循环将停止并从 FileList 中的下一个文件重新开始? 我尝试过使用 break 和 continue 这样做,但都没有做任何事情:
for fname in FileList:
Session = pd.read_csv(fname, header = 3, usecols = [0, 1])
Session = Session[Session['System'].str.contains('Day', na=False)]
Session = Session['No System Name'].tolist()
CRFs = sum(["CRF" in x for x in Session])
if CRFs == len(Session) is True:
continue(or break)
...
df.to_csv(path + 'test_' + fname , index = 0)
非常感谢!
当某些情况发生时,您可以中断主循环,请查看有关此主题的official documentation。
是的!我相信 continue 语句正是您要找的。
执行时,continue
语句将导致当前循环迭代的执行结束,并开始下一次迭代。
来自 python 文档的示例:
>>> for num in range(2, 10):
... if num % 2 == 0:
... print("Found an even number", num)
... continue
... print("Found an odd number", num)
...
Found an even number 2
Found an odd number 3
Found an even number 4
Found an odd number 5
Found an even number 6
Found an odd number 7
Found an even number 8
Found an odd number 9
而不是您的代码中的以下内容:
if CRFs == len(Session) is True:
continue
就这样:
if CRFs == len(Session):
continue