首页 > 解决方案 > 使用列表追加方法将 1M 行插入数据帧太慢

问题描述

我想将大约 100 万行附加到数据场。目前的方法需要很长时间并且是易裂的。以下是我正在做的事情:

要在每次迭代中附加的示例行:

['Offer_5', 'Offer_4', 'Offer_12', 'Offer_8', 'Offer_10', 'Offer_2', 1000065]

示例代码如下:

cols = ['OFFER_CODE_1','OFFER_CODE_2','OFFER_CODE_3','OFFER_CODE_4','OFFER_CODE_5','OFFER_CODE_6','ID']

final_lst_appened = []
for index, row in df.iterrows():
    final_lst = []
    #some processing to get a row as stated above
    final_lst_appened.append(final_lst)

new_df = pd.DataFrame(columns=cols, data = final_lst_appened)

标签: pythonlistdataframedictionary

解决方案


一个小的性能提升可能会更改iterrows()itertuples,如下所述:https ://medium.com/swlh/why-pandas-itertuples-is-faster-than-iterrows-and-how-to-make-it-even-更快-bc50c0edd30d。否则,如果生成每一行的 for 循环中的代码计算量很大,您可能需要查看多处理 ( https://docs.python.org/2/library/multiprocessing.html )。类似于以下内容:

from multiprocessing import Pool
from os import cpu_count

with Pool(cpu_count()) as pool:
    pool.map(func, list(df.itertuples()))

func您申请从原始行生成行的函数在哪里。


推荐阅读