python - 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
解决方案
这就是我要做的:
# 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
推荐阅读
- esp8266 - 构建 esp-open-sdk - crosstool-NG 找不到 expat-2.1.0
- pine-script - PineScript - 通过 TradingView 策略在“n+ 根蜡烛柱”收盘或某个“%”后信号生成后进行交易
- html - 如何在flutter中解析特定数据html
- powershell - 为 powershell 进程提供名称
- sql - 如何从 DateTime 中减去整数秒数
- java - 如何在 intellij 中生成 gradle 运行配置?
- python - 导入另一个以数字开头的 .py 文件
- qt5 - 使用 Gstreamer 在嵌入式 Linux 上的 Qt 小部件中嵌入单独的视频流
- swift - 快速添加随机字母数字字符串的每个第 n 个字符
- javascript - 如何使用 jQuery 之类的嘶嘶声来选择和执行所选元素的操作?