从Pandas栏到木瓦的最快方法

2024-10-01 22:34:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要一种尽可能快的方法从一个数据帧中抹去字符串,然后创建一个主列表。在

给定以下数据帧:

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

我想生成一个列表,木片字符串(长度为3),如下所示: (包括所有可能的3个字母组合。)

^{pr2}$

。。。所有唯一值的主列表如下:

['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']

提前谢谢!在


Tags: 数据方法字符串inimporthello列表for

热门问题