有效地找到字符串列表中的所有子字符串

时间:2018-09-13 08:12:18

标签: python string pandas search

想象一个大的pandas数据帧,由

给出
import string
import random
import pandas as pd

n = 10000

def id_generator(chars=string.ascii_uppercase + string.digits, size=6):
    return ''.join(random.choice(chars) for _ in range(size))


mfr = [id_generator(size=random.randint(3, 20)) for _ in range(n)]
desc = [id_generator(size=random.randint(3, 50)) +
        (' ' + random.choice(mfr) if random.random() > 0.8 else '') for _ in range(n)]

df = pd.DataFrame({'id': range(n), 'mfr': mfr, 'desc': desc}).set_index('id')

产生

                   mfr                                               desc
id                                                                       
0              XACYXAB                            6JYLELA2WUR1MVOS5 1VKF5
1   JOLB082YROZO97PGS5  YWWTUR4A19JKVB5HLBQ9RKVHNJ10J08SQZZHSLG2IB 4MK...
2                 88QO                            DUV566OX9OLSLZJZR9CRWNT
3        DW4S6WTRGWJVE                                                MFE
4             Z2I5VOWK                 IX5DY8GLSPGD5R8W350DZ6ED8CGN2C20GA

对于每个 mfr 值,我希望找到包含该值作为子字符串的 desc ,并返回相应的 id 。可以在pandas中通过

完成此操作
df['matches'] = df.mfr.map(lambda x: df.index[df.desc.str.contains(x)].tolist())

给出理想的结果

                   mfr                                               desc matches
id                                                                               
0              XACYXAB                            6JYLELA2WUR1MVOS5 1VKF5      []
1   JOLB082YROZO97PGS5  YWWTUR4A19JKVB5HLBQ9RKVHNJ10J08SQZZHSLG2IB 4MK...      []
2                 88QO                            DUV566OX9OLSLZJZR9CRWNT      []
3        DW4S6WTRGWJVE                                                MFE      []
4             Z2I5VOWK                 IX5DY8GLSPGD5R8W350DZ6ED8CGN2C20GA      []
5   UPCTNHIF2BOAGOB2WL                  MB2GCMRLQTYD1YRGBJILQ0CZ3LCR2FYHX      []
6              L8K9E3T                                         WW0M73FPD4      []
7                  ZQT               NWNMFRB1ZTMKUVXZH0BFTSIOC3R84XSPRLJS   [532]
8       SPEJJW1JGGSG8B                           7NYL32KTN8ZRNYDV2Z NK4T3      []
9               3WWZ46                Z3HVNIBSQVXJG5487YX7EA89SYPHN5M3BJ2      []

问题是我需要高性能的算法。提供的一个不能很好地扩展。问题是是否存在针对此问题的良好可扩展算法?作为参考,在n = 10000好的台式机上,最后一次通话大约需要42秒。

1 个答案:

答案 0 :(得分:1)

使用嵌套的list comprehension

n = 1000

d = df['desc'].to_dict()

In [117]: %timeit df['matches1'] = [[k for k, v in d.items() if x in v] for x in df.mfr]
80.8 ms ± 2.81 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

In [118]: %timeit df['matches'] = df.mfr.map(lambda x: df.index[df.desc.str.contains(x)].tolist())
877 ms ± 27.1 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)