gpt4 book ai didi

python - 为什么 pandas.series.map 慢得惊人?

转载 作者:太空狗 更新时间:2023-10-30 01:31:30 27 4
gpt4 key购买 nike

有时候我只是讨厌使用中间件。以此为例:我想要一个查找表,将一组输入(域)值的值映射到输出(范围)值。映射是唯一的。 Python map 可以做到这一点,但由于 map 很大,我想,为什么不使用 ps.Series 及其索引,这增加了我可以做到的好处:

  • 传入多个值以映射为一个系列(希望比字典查找更快)
  • 结果中保留了原始系列的索引

像这样:

domain2range = pd.Series(allrangevals, index=alldomainvals)
# Apply the map
query_vals = pd.Series(domainvals, index=someindex)
result = query_vals.map(domain2range)
assert result.index is someindex # Nice
assert (result.values in allrangevals).all() # Nice

按预期工作。但不是。上面的 .map 的时间成本随着 len(domain2range) 而不是(更明智地)O(len(query_vals)) 增长,如图所示:

numiter = 100
for n in [10, 1000, 1000000, 10000000,]:
domain = np.arange(0, n)
range = domain+10
maptable = pd.Series(range, index=domain).sort_index()

query_vals = pd.Series([1,2,3])
def f():
query_vals.map(maptable)
print n, timeit.timeit(stmt=f, number=numiter)/numiter


10 0.000630810260773
1000 0.000978469848633
1000000 0.00130645036697
10000000 0.0162791204453

捂脸。在 n=10000000 时,每个映射值花费 (0.01/3) 秒。

那么,问题:

  • Series.map期望表现得像这样吗?为什么它如此彻底,可笑地慢?我认为我正在按照文档中的说明使用它。
  • 有没有一种使用 pandas 进行表查找的快速方法?上面的好像不是吧?

最佳答案

https://github.com/pandas-dev/pandas/issues/21278

热身是个问题。 (双面手掌)。 Pandas 在首次使用时静默构建并缓存哈希索引 (O(maplen))。调用测试函数并预构建索引可获得更好的性能。

numiter = 100
for n in [10, 100000, 1000000, 10000000,]:
domain = np.arange(0, n)
range = domain+10
maptable = pd.Series(range, index=domain) #.sort_index()

query_vals = pd.Series([1,2,3])

def f1():
query_vals.map(maptable)
f1()
print "Pandas1 ", n, timeit.timeit(stmt=f1, number=numiter)/numiter

def f2():
query_vals.map(maptable.get)
f2()
print "Pandas2 ", n, timeit.timeit(stmt=f2, number=numiter)/numiter

maptabledict = maptable.to_dict()
query_vals_list = pd.Series([1,2,3]).tolist()

def f3():
{k: maptabledict[k] for k in query_vals_list}
f3()
print "Py dict ", n, timeit.timeit(stmt=f3, number=numiter)/numiter
print

pd.show_versions()
Pandas1 10 0.000621199607849
Pandas2 10 0.000686831474304
Py dict 10 2.0170211792e-05

Pandas1 100000 0.00149286031723
Pandas2 100000 0.00118808984756
Py dict 100000 8.47816467285e-06

Pandas1 1000000 0.000708899497986
Pandas2 1000000 0.000479419231415
Py dict 1000000 1.64794921875e-05

Pandas1 10000000 0.000798969268799
Pandas2 10000000 0.000410139560699
Py dict 10000000 1.47914886475e-05

...虽然 python 字典快 10 倍有点令人沮丧。

关于python - 为什么 pandas.series.map 慢得惊人?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50633939/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com