首页 > 解决方案 > 识别不同大小列表中匹配字符串的索引

问题描述

我有要比较的关键字列表和数据列表。当任何字符串匹配时,我希望返回值为 1 的 float64。

import pandas as pd
import numpy as np

data=[['history', 'brain', 'scale', 'imaging', 'patterned', 'optogenetics', 'cellular', 'resolution'], ['infectious', 'fun', 'energy', 'iron', 'oxide', 'nanoparticles'], ['billie', 'holiday', 'project', 'bridging', 'art', 'local', 'history', 'community', 'wellness']]
keywords=[['history', 'literature', 'arts', 'humanities', 'philosophy', 'nan'], ['energy', 'optimization', 'systems', 'healthcare', 'policy', 'public', 'health']]
match=np.zeros(shape=(len(data),len(keywords)))
match=pd.DataFrame(match)

data=pd.DataFrame(data)
keywords=pd.DataFrame(keywords)
compare=data.isin(keywords)

目前它只找到“历史”的第一个例子,但还有第二个,它没有找到“能量”这个词。我希望输出为:

print(match)
     0    1
0  1.0  0.0
1  0.0  1.0
2  1.0  0.0

我尝试了几种不同的 itertools 方法并枚举了没有运气的循环,任何想法将不胜感激。谢谢!

标签: pythonstring-matching

解决方案


只需要一堆循环,更好的想法表示赞赏!

for z in range(len(data)):
    for x in data[z]:
        for q in range(len(keywords)):
            for s in keywords[q]:
                if x==s:
                    match.iloc[z,q]+=1

推荐阅读