首页 > 解决方案 > Pandas Dataframe 的 Bigram Finder

问题描述

我有一个二元组列表。
我有一个 pandas 数据框,其中包含我语料库中每个文档的一行。我要做的是将每个文档中我的列表中匹配的二元组放入我的数据框中的新列中。完成这项任务的最佳方法是什么?我一直在寻找关于堆栈溢出的答案,但没有找到可以给我一个我正在寻找的具体答案的东西。我需要新列来包含从我的二元组列表中找到的每个二元组。

任何帮助,将不胜感激!

我在下面的输出是我正在寻找的,尽管在我的真实示例中,我使用了停用词,因此没有像下面的输出那样找到精确的二元组。有没有办法处理某种字符串包含?

import pandas as pd 
data = [['help me with my python pandas please'], ['machine learning is fun using svd with sklearn']] 
# Create the pandas DataFrame 
df = pd.DataFrame(data, columns = ['Message']) 
import numpy as np
bigrams =[('python', 'pandas'),
 ('function', 'input'),
 ('help', 'jupyter'),
 ('sklearn', 'svd')]
def matcher(x):
    for i in bigrams:
        if i.lower() in x.lower():
            return i
    else:
        return np.nan

df['Match'] = df['Message'].apply(matcher)
df

标签: pythonpandasnlp

解决方案


这就是我要做的:

# a sample, which you should've given
df = pd.DataFrame({'sentences': ['I like python pandas', 
                                 'find all function input from help jupyter',
                                 'this has no bigrams']})


# the bigrams
bigrams = [('python', 'pandas'),
 ('function', 'input'),
 ('help', 'jupyter'),
 ('sklearn', 'svd')]

# create one big regex pattern:
pat = '|'.join(" ".join(x) for x in bigrams)

new_df = df.sentences.str.findall(pat)

给你

0                   [python pandas]
1    [function input, help jupyter]
2                                []
Name: sentences, dtype: object

然后您可以选择在每一行中取消嵌套列表。

或者您可以使用get_dummies

new_df.str.join(',').str.get_dummies(sep=',')

这给了你:

  function input  help jupyter  python pandas
0               0             0              1
1               1             1              0
2               0             0              0

推荐阅读