【发布时间】:2017-05-13 00:48:26
【问题描述】:
ID outcome Source_doc
23145 A ARR
23145 A CRE
23145 B ARR
23145 C CRE
23456 B ARR
23456 B CRE
来自 ARR 的 ID #145 具有 [A,B] 结果。来自 CRE 的 ID #145 具有 [A,C] 结果。您可以在下面看到我会将 ID #145 放在“not_same_list”中。我的数据集包括 445,000 行。我执行的过程每 100 行需要 21 秒。所以这将需要7个多小时!
这个循环中最慢的部分是什么?
我执行 Pandas 搜索的效率最高吗?
iterrows() 会更快吗?
编辑:关于预期输出的要点。我实际上只是期待一个 ID 列表。如果 AAR_list 和 CRE_list 不相同,我想标记该 ID 并将其放入列表 (not_same_list)。所以我正在寻找 [145, 178, ..., 989, (任何结果与源文档不匹配的 ID)]
not_same_list = []
total_search_start_time = time.time()
tick = 0
for IDs in uniq_IDs['ID'].unique():
#Isolate rows by their ID and source doc
sco_ARR = uniq_IDs['outcome'][uniq_IDs['ID'] == IDs][uniq_IDs['Source_Doc'] == 'ARR']
sco_CRE = uniq_IDs['outcome'][uniq_IDs['ID'] == IDs][uniq_IDs['Source_Doc'] == 'CRE']
#Remove duplicates
ARR_list = set(sco_ARR.values.tolist())
CRE_list = set(sco_CRE.values.tolist())
#Check to see if outcomes match between source docs
if ARR_list != CHRI_list:
not_same_list.append(IDs)
if str(tick)[-2:] == '00':
print ('The last {} rows have taken {} seconds...'.format(tick,round(time.time()-total_search_start_time,2)))
tick += 1
else:
tick += 1
print ('The last {} rows have taken {} seconds...'.format(tick,round(time.time()-total_search_start_time,2)))
print (not_same_list)
如果有人可以为这个问题制作一个更好的表格,请这样做:
【问题讨论】:
-
我怀疑
drop_duplicates方法会有所帮助。 -
你能不能也放下预期的输出?
-
除了 Jack Maney 的建议之外,我认为 pandas 代码中的一般危险信号是使用
for循环。将其组合为向量/矩阵运算通常会加快速度。 -
实际上,格式关闭了吗?在我看来,你在这里的 for 循环只是一遍又一遍地设置,而不是使用
ARR_list和CRE_list。我同意 John Galt 的观点,您应该提供预期的输出,以便更清楚您想要做什么。
标签: python arrays performance loops pandas