簡體   English   中英

如果在遍歷 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 循環 I go 通過應用我的代碼的路徑中的所有文件。

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 的長度等於 CRFs 循環將停止並使用 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)

提前謝謝了!

而不是在您的代碼中:

if CRFs == len(Session) is True: 
    continue

做就是了:

if CRFs == len(Session):
    continue

是的! 我相信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

當某些情況發生時,您可以中斷主循環,請查看有關此主題的官方文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM