【问题标题】:python script for keyword match between two dataframes用于两个数据帧之间关键字匹配的python脚本
【发布时间】:2020-12-28 22:11:06
【问题描述】:

我想创建一个预处理函数,根据 Excel 表中给出的数据进行关键字匹配。

import pandas as pd
import numpy as np

#text1 = "text string for keyword match"
#text2 = "hello world"
# single row dataframe
stri = [["ABC", "text string for keyword match"]]
df = pd.DataFrame(stri, columns = ['Name', 'Subject'])

#Sample keyword excel file converted to dataframe

kwlist = [['File', 'startswith', 'A1'],['sample', 'startswith', 'B2'],['text', 'startswith', 'C3'],['earth', 'contains', 'D4'],['world', 'contains', 'E5']]
km = pd.DataFrame(kwlist , columns =['keyword', 'Process', 'label'])

我想将 df 与 km 进行比较,如果关键字匹配,则基于以 km 给出的“进程”并从 km 中获取相应的输出“标签”。

我正在尝试使用此功能。


lists = km['keyword'].tolist()

def keymatch(text):
    for i in lists:
        p = np.where(df['Subject'].str.startswith(i) == True)[0]
        q = np.where(df['Subject'].str.contains(i) == True)
        if df['Subject'].str.contains(i).all() == True:

            if df['Subject'].str.startswith(i).all() == True:
                #p = np.where(df['Subject'].str.startswith(i) == True)[0]
                print(km['label'].iloc[p])
                print("Startswith")
            else:
                #q = np.where(df['Subject'].str.contains(i) == True)
                print(km['label'].iloc[q])
                print("Contains")
        else:
            print("use other code")

keymatch(df['Subject'].iloc[0])

我总是得到输出“A1”。

预期输出:

例如,如果字符串是“hello world”,那么它的进程类型应该是包含并返回输出“E5”。

如果字符串是'用于关键字匹配的文本字符串',那么进程应该是startswith并返回一个输出'C3'

【问题讨论】:

  • 你能发布预期的输出吗
  • 给定代码的'C3'
  • df 总是有单行吗?
  • 是的,现在输入的是单行的 excel(df)。

标签: python pandas dataframe loops


【解决方案1】:

不是一个有效的解决方案,但这会起作用

res = km.loc[km.apply(lambda x: any(x.keyword in y for y in df.Subject), axis=1), 'label']
print(res)

输出:

2    C3
Name: label, dtype: object

比如df这样的

  Name                        Subject
0  ABC  text string for keyword match
1  XYZ                    hello world

它会给出输出

2    C3
4    E5
Name: label, dtype: object

【讨论】:

  • 感谢您的回答!但是即使在字符串中间出现带有 Process 的单词时,它也会给出输出。例如“文本关键字匹配脚本的字符串”仍将返回 C3,但输出应为空。
  • 那么您应该根据Process 列使用kmdf 创建新的数据框
猜你喜欢
  • 1970-01-01
  • 2019-03-16
  • 2012-08-20
  • 1970-01-01
  • 1970-01-01
  • 2020-11-28
  • 1970-01-01
  • 1970-01-01
  • 2022-10-07
相关资源
最近更新 更多