从 Pandas 列到瓦片的最快方法

Fastest Way to Shingle from Pandas Column

我需要尽可能快的方法来从数据框中拼接字符串,然后创建主列表。

给定以下数据框:

import pandas as pd
d=['Hello', 'Helloworld']
f=pd.DataFrame({'strings':d})
f
    strings
0   Hello
1   Helloworld

我想生成一个这样的带状字符串列表(长度为 3): (包括所有可能的 3 字母组合。)

[['Hel', 'ell', 'llo'],['Hel', 'ell', 'llo', 'low', 'owo', 'wor', 'orl', 'rld']]

...以及所有唯一值的主列表,如下所示:

['wor', 'Hel', 'ell', 'owo', 'llo', 'rld', 'orl', 'low']

我可以按如下方式进行,但我怀疑有更快的方法:

#Shingle into strings of exactly 3
def shingle(word):
    r = [word[i:i + 3] for i in range(len(word) - 3 + 1)]
    return [''.join(t) for t in r]
#Shingle (i.e. "hello" -> "hel","ell",'llo')
r=[shingle(w) for w in f['strings']]
#Get all elements into one list:
import itertools
colsunq=list(itertools.chain.from_iterable(r))
#Remove duplicates:
colsunq=list(set(colsunq))
colsunq

['wor', 'Hel', 'ell', 'owo', 'llo', 'rld', 'orl', 'low']

提前致谢!

我迟到了 4 年,但这里有一个答案。我认为不可能确定“最快”的方式,因为这在很大程度上取决于硬件和算法。 (它可能属于类似于 Kolmogorov complexity 的内容。)

但是,我需要合并超过 1100 万个文件。我把每个单词放在一个 numpy 数组中,运行 下面的代码。

shingles = set()

for i in range(words.shape[0] - w + 1):
    a = words[i:i + w]
    shingles.add(tuple(a))

此代码在大约 6 小时内处理了 272 亿个单词。

如果你想拼接一系列单词,这很有效:

def shingles(word, n = 3):
    return [word[i:i + n] for i in range(len(word) - n + 1)]

df['shingles'] = df2.to_shingle_col.map(shingles)

所以,如果你有类似的东西

[123,456,789,123,456]你会得到

[[123,456,789],[456,789,123],[789,123,456]]