搜索数据框并输出匹配的值

时间:2019-04-01 06:27:19

标签: python pandas

我有两个CSV(News.csv和Country.csv),我试图通过Country.csv中可用的国家/地区名称列表在News.csv中搜索一个国家/地区名称。

我能够找到是否存在匹配项并显示布尔值。

新闻CSV

News head

国家CSV

Country head

news.dropna(inplace = True)
news.drop_duplicates(keep='first', inplace = True)
country_list = country['Country'].values
import warnings
warnings.filterwarnings("ignore", 'This pattern has match groups')
news['Test'] = news['Title'].str.contains('|'.join(country_list), case = 
False, regex = True)

在“标题”列上执行搜索之后

Search

但是我想显示匹配的国家。此外,有没有一种方法可以一次查询多个列?例如,一次搜索标题和网址。

1 个答案:

答案 0 :(得分:1)

我相信您需要将各列连接在一起

pat = '|'.join(country_list)
s = news['url'].add(news['Title'])

对于第一个比赛,请使用Series.str.extract

news['Test'] = s.str.extract('('+ pat + ')', flags=re.I, expand=False)

对于所有匹配项,请使用Series.str.findall作为列表,如果需要带分隔符的字符串,请添加Series.str.join

news['Test'] = s.str.extract(pat, flags=re.I).str.join(', ')