python - 如何在 Pandas 数据框列中查找关键字并通过虚拟变量分配标签?

标签 python pandas dataframe text-mining

我不知道如何给这个抱歉起标题。基本上,我有一个包含关键字和标签的 CSV 文件。它看起来像这样:

col Keyword   Tag

0   Keyword1  Tag1 
1   Keyword2  Tag1 
2   Keyword3  Tag2 
3   Keyword4  Tag2
4   Keyword5  Tag3 
5   Keyword6  Tag3

我有一个包含这些列的单独数据框:

col Name  Description  Tag 1  Tag 2  Tag 3 
0   A     ..Keyword1..
1   B     ..Keyword4..
2   C     ..Keyword5..
3   D     ..Keyword4..
4   E     ..Keyword2..
...

我想遍历我的数据框的每一行,并检查描述以查看它是否包含 CSV 文件中的任何关键字。如果是这样,我想将相应的“标签”列设置为 1,否则为 0,如下所示:

col Name  Description  Tag 1  Tag 2  Tag 3 
0   A     ..Keyword1..  1      0      0
1   B     ..Keyword4..  0      1      0
2   C     ..Keyword5..  0      0      1
3   D     ..Keyword4..  0      1      0
4   E     ..Keyword2..  1      0      0
...

这就是我创建数据框的方式:

import pandas as pd

df = pd.read_csv('dataframe_file.csv')
keys = pd.read_csv('keyword_file.csv')

df2 = keys.groupby('tag').apply(lambda x: x['keyword'].unique())
for keyword in df2.index:
    df[keyword] = ''

我的 df2 是什么样子的:

col Tag                                                            Keywords
access bypass                                                      [access bypass]
access control                   [access control, dma access control, trigger a...
already admin                               [have valid administrative privileges]
ansi escape                                                          [ansi escape]
application execution                                     [cause a service to run]

我试过这样的东西但很快就卡住了:

for keyword in df2.index:
    for tag in df2:
        for word in tag:
            for row in df:
                if word in df.iloc[]

这是一个数据示例

col Name Description AccessControl AlreadyAdmin ArrayAccess .... xmlInjection xmlParsing
0   CVE1 Long Desc
1   CVE2 Long Desc
2   CVE3 Long Desc
3   CVE4 Long Desc

最佳答案

IIUC,这样做可以:

# toy data
df = pd.DataFrame({'Description': ['This contains Keyword 1', 'This contains Keyword 4',
                                   'This contains Keyword 4  and Keyword 6']})


pattern = '|'.join(keys.keyword)
(df.Description
   .str.extractall(f'({pattern})')[0]
   .map(keys.set_index('keyword')['tag'])
   .reset_index(name='col')
   .assign(value=1)
   .pivot_table(index='level_0', columns='col', values='value', fill_value=0)

)

输出:

col      Tag 1  Tag 2  Tag 3
level_0                     
0            1      0      0
1            0      1      0
2            0      1      1

关于python - 如何在 Pandas 数据框列中查找关键字并通过虚拟变量分配标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59219591/

相关文章:

Python根据范围将一列拆分为多列

python - 从所有其他行中减去每一行并在 python 中查看为矩阵

python - Cygwin:导入 numpy 错误

python - 获取整数的第 n 个字节

python - 文本小部件内 Tkinter 中的滚动条

python - 使用索引数组切片 Pandas 数据框

Pandas 数据框通过 .loc 一次创建多行

python和数据帧: group by week and calculate the sum and difference

python-3.x - 如何识别两个数据帧之间的精确行匹配并打印其上方的行

python - 为什么我的 setuptools 无法在 Python 3.9 中运行?