【发布时间】:2020-01-05 12:41:06
【问题描述】:
我有一个python 脚本,内容如下:
- 我有一个 json 列表
- 我创建了一个空的
pandas数据框 - 我在这个列表上运行了一个 for 循环
- 我在每次迭代时使用(相同的)键创建一个空字典,这对我来说很有趣
- 我在每次迭代时解析 json 以检索键的值
- 我在每次迭代时将字典附加到
pandas数据帧
这样做的问题是,在每次迭代中,处理时间都在增加。 具体来说:
0-1000 documents -> 5 seconds
1000-2000 documents -> 6 seconds
2000-3000 documents -> 7 seconds
...
10000-11000 documents -> 18 seconds
11000-12000 documents -> 19 seconds
...
22000-23000 documents -> 39 seconds
23000-24000 documents -> 42 seconds
...
34000-35000 documents -> 69 seconds
35000-36000 documents -> 72 seconds
为什么会这样?
我的代码如下所示:
# 'documents' is the list of jsons
columns = ['column_1', 'column_2', ..., 'column_19', 'column_20']
df_documents = pd.DataFrame(columns=columns)
for index, document in enumerate(documents):
dict_document = dict.fromkeys(columns)
...
(parsing the jsons and retrieve the values of the keys and assign them to the dictionary)
...
df_documents = df_documents.append(dict_document, ignore_index=True)
附言
在下面应用@eumiro 的建议后,时间如下:
0-1000 documents -> 0.06 seconds
1000-2000 documents -> 0.05 seconds
2000-3000 documents -> 0.05 seconds
...
10000-11000 documents -> 0.05 seconds
11000-12000 documents -> 0.05 seconds
...
22000-23000 documents -> 0.05 seconds
23000-24000 documents -> 0.05 seconds
...
34000-35000 documents -> 0.05 seconds
35000-36000 documents -> 0.05 seconds
在应用@DariuszKrynicki 的建议后,时间如下:
0-1000 documents -> 0.56 seconds
1000-2000 documents -> 0.54 seconds
2000-3000 documents -> 0.53 seconds
...
10000-11000 documents -> 0.51 seconds
11000-12000 documents -> 0.51 seconds
...
22000-23000 documents -> 0.51 seconds
23000-24000 documents -> 0.51 seconds
...
34000-35000 documents -> 0.51 seconds
35000-36000 documents -> 0.51 seconds
...
【问题讨论】:
-
@JohnColeman, 1) 它可能不同于
..., 2) 如果...是二次的,那么它在每次迭代中不会大致相同?或者如果不一样,它每次都会波动(有时更低,有时更高)?但在这里,正如您所见,它只会稳步增加。 -
这是因为您的 df_documents 正在增长。
-
@JohnColeman,关于我在下面的第 (1) 点,请参阅下面其他人的答案。 (你删评论就离开战场了?哈哈)
标签: python pandas performance for-loop time