1 回答

TA貢獻1831條經(jīng)驗 獲得超10個贊
循環(huán)的一般語法for是
for target in expression:
do all the things
Python 會將表達式計算為一個對象,只有當計算完成時,它才會將該對象分配給目標變量。這意味著任何已存在的對象在target其替換對象構(gòu)建完成之前都不會被刪除。
除非創(chuàng)建的對象很大,否則這沒什么大不了的。這里就是這種情況。創(chuàng)建新塊時,即將刪除的塊位于內(nèi)存中,這實際上使對內(nèi)存的影響加倍。解決方案是在返回更多目標之前手動刪除循環(huán)中的目標。
for chunk in pd.read_csv(fname, chunksize=chunksize,sep='|',error_bad_lines=False):
chunk['col1'] = chunk['col1'].apply(process1)
chunk['col2'] = chunk['col2'].apply(process2)
if c == 0:
chunk.to_csv("result/result.csv", index=False)
else:
chunk.to_csv('result/result.csv', mode='a', header=False, index=False)
del chunk # destroy dataframe before next loop to conserve memory.
if c%10==0:
print(c)
c+=1
添加回答
舉報