我的目标是检查我的数据框列,如果该列包含字符串列表中的项目(在 ex 中匹配),那么我想创建一个包含所有匹配项目的新数据框。
使用我当前的代码,我可以获取匹配的列的列表,但是,它将它作为一个列表,我想使用我之前拥有的信息创建一个新的数据框。
这是我当前的代码 - 我想要我以前拥有的整个数据帧信息,而不是生成一个列表
matches = ['beat saber', 'half life', 'walking dead', 'population one']
checking = []
for x in hot_quest1['all_text']:
if any(z in x for z in matches):
checking.append(x)
Run Code Online (Sandbox Code Playgroud)
Pandas 通常允许您过滤数据帧,而无需诉诸for循环。
这是一种应该有效的方法:
matches = ['beat saber', 'half life', 'walking dead', 'population one']
# matches_regex is a regular expression meaning any of your strings:
# "beat saber|half life|walking dead|population one"
matches_regex = "|".join(matches)
# matches_bools will be a series of booleans indicating whether there was a match
# for each item in the series
matches_bools = hot_quest1.all_text.str.contains(matches_regex, regex=True)
# You can then use that series of booleans to derive a new data frame
# containing only matching rows
matched_rows = hot_quest1[matches_bools]
Run Code Online (Sandbox Code Playgroud)
这是该方法的文档str.contains。
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.contains.html