Pandas Dataframe 性能与列表性能

mar*_*rie 9 python pandas

我正在比较两个数据帧以确定 df1 中的行是否以 df2 中的任何行开头。df1 的数量为一千个条目,df2 的数量为数百万个。

这可以完成工作,但速度相当慢。

df1['name'].map(lambda x: any(df2['name'].str.startswith(x)))
Run Code Online (Sandbox Code Playgroud)

在 df1(10 项)的子集上运行时,结果如下:

35243     True
39980    False
40641    False
45974    False
53788    False
59895     True
61856    False
81083     True
83054     True
87717    False
Name: name, dtype: bool
Time: 57.8873581886 secs
Run Code Online (Sandbox Code Playgroud)

当我将 df2 转换为列表时,它运行得更快:

df2_list = df2['name'].tolist()

df1['name'].map(lambda x: any(item.startswith(x + ' ') for item in df2_list))

35243     True
39980    False
40641    False
45974    False
53788    False
59895     True
61856    False
81083     True
83054     True
87717    False
Name: name, dtype: bool
Time: 33.0746209621 secs
Run Code Online (Sandbox Code Playgroud)

为什么遍历列表比遍历系列更快?

HYR*_*YRY 5

any()当它获得True值时会提前返回,因此startswith()调用次数少于Dataframe版本。

这是一种使用的方法searchsorted()

import random, string
import pandas as pd
import numpy as np

def randomword(length):
    return ''.join(random.choice(string.ascii_lowercase) for i in range(length))


xs = pd.Series([randomword(3) for _ in range(1000)])
ys = pd.Series([randomword(10) for _ in range(10000)])

def is_any_prefix1(xs, ys):
    yo = ys.sort_values().reset_index(drop=True)
    y2 = yo[yo.searchsorted(xs)]
    return np.fromiter(map(str.startswith, y2, xs), dtype=bool)

def is_any_prefix2(xs, ys):
    x = xs.tolist()
    y = ys.tolist()
    return np.fromiter((any(yi.startswith(xi) for yi in y) for xi in x), dtype=bool)

res1 = is_any_prefix1(xs, ys)
res2 = is_any_prefix2(xs, ys)
print(np.all(res1 == res2))

%timeit is_any_prefix1(xs, ys)
%timeit is_any_prefix2(xs, ys)
Run Code Online (Sandbox Code Playgroud)

输出:

True
100 loops, best of 3: 17.8 ms per loop
1 loop, best of 3: 2.35 s per loop
Run Code Online (Sandbox Code Playgroud)

速度快了 100 倍。