请帮助我理解为什么Python/Pandas中的"替换字典"操作很慢:
# Series has 200 rows and 1 column
# Dictionary has 11269 key-value pairs
series.replace(dictionary, inplace=True)
Run Code Online (Sandbox Code Playgroud)
字典查找应为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.')
Run Code Online (Sandbox Code Playgroud)
在我的机器上运行该命令需要1秒以上的时间,这比执行<1000次操作的时间长1000倍.
双方pandas.Series.map并pandas.Series.replace似乎给了相同的结果。是否有理由使用一个而不是另一个?例如:
import pandas as pd
df = pd.Series(['Yes', 'No'])
df
0 Yes
1 No
dtype: object
Run Code Online (Sandbox Code Playgroud)
df.replace(to_replace=['Yes', 'No'], value=[True, False])
0 True
1 False
dtype: bool
Run Code Online (Sandbox Code Playgroud)
df.map({'Yes':True, 'No':False})
0 True
1 False
dtype: bool
Run Code Online (Sandbox Code Playgroud)
df.replace(to_replace=['Yes', 'No'], value=[True, False]).equals(df.map({'Yes':True, 'No':False}))
True
Run Code Online (Sandbox Code Playgroud)