python - 使用列表追加方法将 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)
解决方案
一个小的性能提升可能会更改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
您申请从原始行生成行的函数在哪里。
推荐阅读
- jgit - 为什么 jGit RemoteAdd 命令不像其他命令那样链接?
- c# - 从 Windows CE 到 Windows Azure 的 https Web API 调用不再有效
- angularjs - calendar.ui/fullCalendar - 营业时间问题
- gnuplot - 频率图最后一个不同宽度的框
- javascript - 如何在应用程序 electron.js 中使用票证 kerberos?
- entity-framework - 如何使用具有多个 dbcontexts 的实体框架迁移,将不同的域类映射到同一个表
- node.js - 从 Http-Server 中的请求中获取 IP 地址
- swift - Swift单按钮处理录音,暂停和恢复
- python - Python在本地包中导入本地包时遇到问题
- c++ - 如何分配 N(非常量变量)对的向量并初始化它们?