虽然迭代行不是好的做法,并且可以使用 grouby/transform 聚合等替代逻辑,但如果在最坏的情况下您确实需要这样做,请遵循答案。此外,您可能不需要在这里重新实现所有内容,您可以使用 Dask 之类的库,它构建在 pandas 之上。
但只是为了提供想法,您可以将multiprocessing (Pool.map) 与chunking 结合使用。读取块中的csv(或在答案末尾提到的制作夹头)并将其映射到池中,在处理每个块时添加新行(或将它们添加到列表并制作新块)并从函数中返回。
最后在所有池执行完毕后合并数据帧。
import pandas as pd
import numpy as np
import multiprocessing
def process_chunk(df_chunk):
for index, row in df_chunk.reset_index(drop = True).iterrows():
#your logic for updating this chunk or making new chunk here
print(row)
print("index is " + str(index))
#if you can added to same df_chunk, return it, else if you appended
#rows to have list_of_rows, make a new df with them and return
#pd.Dataframe(list_of_rows)
return df_chunk
if __name__ == '__main__':
#use all available cores , otherwise specify the number you want as an argument,
#for example if you have 12 cores, leave 1 or 2 for other things
pool = multiprocessing.Pool(processes=10)
results = pool.map(process_chunk, [c for c in pd.read_csv("your_csv.csv", chunksize=7150)])
pool.close()
pool.join()
#make new df by concatenating
concatdf = pd.concat(results, axis=0, ignore_index=True)
注意:您可以通过相同的逻辑传递chucks,而不是读取csv,来计算块大小,您可能需要round_of( (length of df) / (number of core available-2)) 例如100000/14 = round(7142.85) = 7150 rows 每个块
results = pool.map(process_chunk,
[df[c:c+chunk_size] for c in range(0,len(df),chunk_size])