Skip to main content
 首页 » 编程设计

python之Pandas N-Grams 到列

2024年10月17日8lexus

给定以下数据框:

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

我想将每个字符串拆分为 3 个字符的 block ,并使用它们作为标题来创建 1 或 0 的矩阵,具体取决于给定行是否具有 3 个字符的 block 。

像这样:

    Strings     Hel     low     orl 
0   Hello         1       0       0 
1   Helloworld    1       1       1 

请注意,字符串“Hello”的“低”列为 0,因为它仅为完全部分匹配分配 1。如果有超过 1 个匹配项(即,如果字符串是“HelHel”,它仍然只会分配一个 1(尽管知道如何计算它并因此分配一个 2 也很好)。

最终,我正在尝试通过 SKLearn 在 LSHForest 中为我们准备数据。 因此,我预计会有许多不同的字符串值。

这是我到目前为止尝试过的:

#Split into chunks of exactly 3 
def split(s, chunk_size): 
    a = zip(*[s[i::chunk_size] for i in range(chunk_size)]) 
    return [''.join(t) for t in a] 
cols=[split(s,3) for s in f['strings']] 
cols 
 
[['Hel'], ['Hel', 'low', 'orl']] 
 
#Get all elements into one list: 
import itertools 
colsunq=list(itertools.chain.from_iterable(cols)) 
#Remove duplicates: 
colsunq=list(set(colsunq)) 
colsunq 
 
['orl', 'Hel', 'low'] 

所以现在,我需要做的就是为 colsunq 中的每个元素在 f 中创建一个列,如果 'strings' 列中的字符串有一个与每个给定列标题的 block 匹配。

提前致谢!

注意: 如果首选叠瓦:

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

请您参考如下方法:

def str_chunk(s, k): 
    i, j = 0, k 
    while j <= len(s): 
        yield s[i:j] 
        i, j = j, j + k 
 
def chunkit(s, k): 
    return [_ for _ in str_chunk(s, k)] 
 
def count_chunks(s, k): 
    return pd.value_counts(chunkit(s, k)) 

示范

f.strings.apply(chunkit, k=3) 
 
0              [Hel] 
1    [Hel, low, orl] 
Name: strings, dtype: object 
 
f.strings.apply(count_chunks, k=3).fillna(0) 


带状疱疹

def str_shingle(s, k): 
    i, j = 0, k 
    while j <= len(s): 
        yield s[i:j] 
        i, j = i + 1, j + 1 
 
def shingleit(s, k): 
    return [_ for _ in str_shingle(s, k)] 
 
def count_shingles(s, k): 
    return pd.value_counts(shingleit(s, k)) 
 
f.strings.apply(count_shingles, k=3).fillna(0)