python - 无法生成列表以显示列表中的任何匹配项

标签 python pandas dataframe lambda apply

我正在尝试使数据框的一列与列表匹配(如果有的话)。为此创建了一个名为 return hits 的自定义函数。

def returnhits(a_list, long_string):
    matches =[]
    for match in a_list:
        if any(word in long_string.split() for match in a_list):
            matches.append(match)
    return ' , '.join(matches)
qualification_list = ('Professional Certificate', 'NiTEC ', "Bachelor's Degree", 'Diploma', 'Advanced/Higher/Graduate Diploma', 'Post Graduate Diploma' , 'Professional Degree', "Master's Degree" , 'Doctorate (PhD)')

但是我无法产生想要的结果。

df['Qualifications'] = df['Other information'].apply(lambda x : returnhits(qualification_list, x))

理想情况下,如果文本中有匹配项,它将返回 NiTEC ,Professional Degree

最佳答案

你可以试试这个来检查并返回多重匹配:


df = pd.DataFrame({'Other information': ['something', ' Diploma blah NiTEC', 'other Diploma']})
qualification_list = ('Professional Certificate', 'NiTEC', "Bachelor's Degree", 'Diploma', 'Advanced/Higher/Graduate Diploma', 'Post Graduate Diploma' , 'Professional Degree', "Master's Degree" , 'Doctorate (PhD)')

def returnhits(a_list, x):
    return(' , '.join(a for a in a_list if a in x))

df['matches'] = df['Other information'].apply(lambda x : returnhits(qualification_list,x))

print(df)

输出:

     Other information          matches
0            something                 
1   Diploma blah NiTEC  NiTEC , Diploma
2        other Diploma          Diploma

关于python - 无法生成列表以显示列表中的任何匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69161967/

相关文章:

python - 使用 Python 请求 'bridge' 文件而不加载到内存中?

python - Flask 重定向到 url 并传递查询字符串

javascript - 如何使用 python 截取给定 url 的屏幕截图

python - 年化返回均值。

sql - 如何使用selectExpr在spark数据帧中转换结构数组?

python - Python 中 hasattr 的逆运算

python - 在 pyCharm 中安装 Pandas 时出现错误 Microsoft Visual C++ 10.0

Python:如何将 ggplot 与简单的 2 列数组一起使用?

python - 如何在 python 中流入和操作大数据文件

r - 为数据框的每一列计算一个样本 t 检验,并将结果汇​​总在表格中