我想根据以下两个列表筛选我的数据集:
list_1=['important', 'important words', 'terms to have','limone','harry']
list_2=['additional','extra','terms','to check','estate']
在第一行中,我有我真正需要的术语;在{&
和|
条件的混合,但我无法过滤行
如果我有
Date Head Text
03/01/2020 Estate in vacanza marea: cosa fare in caso di ...
03/01/2020 Cosa mangiare in estate il limone è una spezia molto usata durante il periodo estivo
03/01/2020 NaN tutti pazzi per l'estate: “pronto, ma se apro le finestre per arieggiare...
03/01/2020 Harry torna in UK il principe harry torna a buckingham palace in estate...
03/01/2020 Consigli per l'estate Estate come proteggersi -
如您所见,单词estate
几乎出现在所有行中。我需要这个词,但我也需要考虑行“Limon”或“哈里”。
因此,我想过滤如下:
estate + limone # to avoid confusion I mean select estate AND limone
或
estate + harry # to avoid confusion I mean select estate AND harry
在Head
和/或Text
内。我不在乎Head中是否有estate,Text中是否有limone,但我需要两个单词(或estate+harry)可以在同一行中,无论是在两列中还是在一列中。
从我之前的一个问题中,我知道我应该使用
df[['Head','Text']].apply(lambda x : x.str.contains(something)).any(1)
但考虑到两个单独的列表(如问题顶部),我很难添加条件estate+limone或estate+harry。 我目前正在迭代两次:
df=df[df[['Head, Text']].apply(lambda x : x.str.contains('|'.join(list_1))).any(1)]
df=df[df[['Head, Text']].apply(lambda x : x.str.contains('|'.join(list_2))).any(1)]
有没有办法把这两个代码压缩成一个
输出:
Date Head Text
03/01/2020 Cosa mangiare in estate il limone è una spezia molto usata durante il periodo estivo
03/01/2020 Harry torna in UK il principe harry torna a buckingham palace in estate...
如果您能在上面的代码行中解释如何设置此条件,我将不胜感激
我希望我能正确理解这个案例:我们有一个“强制性”词汇列表(如果它们不存在,整行就不相关),还有一个“可取”词汇列表。也许您可以进行内部联接以查找同时包含必填项和所需项的行:
总而言之:
请注意,这是区分大小写的
如果您还需要只分析带有必填词的行,那么第一种方法会更有用。第二种方法可能不太有用,因为强制性和“可取”是等效的(如果两者都需要存在的话)
相关问题 更多 >
编程相关推荐