【发布时间】: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