我正在根据数据框中的姓名列表搜索网页。如果某个名称出现在段落中,我想知道是哪个段落,以便我可以解析该段落的某些部分,然后将其与名称关联起来。
我有两个数据框:
dfrule 由“Paragraphs”和“Ids”组成,而 eldf 由“Names”和“Ids”组成
埃尔夫:
{'Name':{...,
1704: 'Satco',...}}
dfrule:
{'Paragraphs: {0:" Words words words Satco", ...}, 'id': {0: 0,1: 1,...}}
我想要的输出是条目“Satco”及其出现的段落的 ID。
到目前为止我已经:
substring_matches = eldf['name'].apply(lambda s1: dfrule['Paragraphs'].apply(lambda s2: s1 in s2).any()
matchdf = eldf[substring_matches]
这为我提供了列表中与任何段落匹配的每个名称,但不提供与之匹配的段落的 ID。我怎样才能将它与段落 id 关联起来?
所以我明白了
{'Name":{1704:'Satco'}, 'Paragraph id':{0:0}}
由于没有提供数据,我不得不猜测它可能是什么样子。我不完全清楚数据帧的确切参数,也不完全清楚所需的输出格式,但下面是一个示例,如果它们包含“名称”列下的值,您可以找到所有段落 ID,忽略大小写。
如果您希望函数对大小写更加严格,请从 str.contains 调用中删除 'case=False' 参数。
import pandas as pd
dfrule_dict = {'Paragraphs': ['Example paragraph one.', 'Example two.',
'Third example.', 'This is the fourth.'],
'Ids': [1, 2, 3, 4]}
dfrule = pd.DataFrame(dfrule_dict)
eldf_dict = {'Names': ['Example', 'two', 'paragraph', 'Foo', 'Bar', '.', 'Master Chief'],
'Ids': [111, 112, 113, 114, 115, 116, 117]}
eldf = pd.DataFrame(eldf_dict)
def find_paragraphs(name):
ids = dfrule[dfrule['Paragraphs'].str.contains(name, case=False)]['Ids'].tolist()
return ids
eldf['paragraph_ids'] = eldf['Names'].apply(find_paragraphs)
print(eldf)