【发布时间】:2017-06-18 12:59:54
【问题描述】:
请帮助我理解为什么这个“从字典替换”操作在 Python/Pandas 中很慢:
# Series has 200 rows and 1 column
# Dictionary has 11269 key-value pairs
series.replace(dictionary, inplace=True)
字典查找应该是 O(1)。替换列中的值应该是 O(1)。这不是矢量化操作吗?就算不向量化,迭代200行也只是200次迭代,怎么会慢呢?
这是一个 SSCCE 演示该问题:
import pandas as pd
import random
# Initialize dummy data
dictionary = {}
orig = []
for x in range(11270):
dictionary[x] = 'Some string ' + str(x)
for x in range(200):
orig.append(random.randint(1, 11269))
series = pd.Series(orig)
# The actual operation we care about
print('Starting...')
series.replace(dictionary, inplace=True)
print('Done.')
在我的机器上运行该命令需要超过 1 秒的时间,这比执行
【问题讨论】:
-
请提供一个可重现的示例,并定义您所说的“慢”是什么意思。我尝试复制您的设置时没有性能问题,替换需要大约 200 毫秒。
-
使用 SSCCE 编辑了 OP。使用 Python 时,每次操作约 1ms 真的是预期的性能吗?
标签: python performance pandas dictionary