选择熊猫DF行,包括字符串列表中的任何字符串

问题描述 投票:0回答:2

我正在尝试选择“故事”列中包含列表“ selected_words”中任何字符串的行。

我尝试了包括isin和str.contains在内的多个选项,但是我通常只会得到错误,否则将得到一个空的数据框。

df4=pd.read_csv("https://drive.google.com/file/d/1rwg8c2GmtqLeGGv1xm9w6kS98iqgd6vW/view?usp=sharing")
df4["story"] = df4["story"].astype(str) 
selected_words = ['accept', 'believe', 'trust', 'accepted', 'accepts',\
'trusts', 'believes', 'acceptance', 'trusted', 'trusting', 'accepting',\ 'believes', 'believing', 'believed', 'normal', 'normalize', ' normalized',\ 'routine', 'belief', 'faith', 'confidence', 'adoption', \
'adopt', 'adopted', 'embrace', 'approve', 'approval', 'approved', 'approves']
#At this point I am lost as to what to do next

根据我尝试执行的操作,我得到一个空的数据框或一条错误消息。

python pandas
2个回答
1
投票

尝试一下。我无法加载您的DF。

df4[df4["story"].isin(selected_words)]

0
投票

在这里您可以看到解决方案https://stackoverflow.com/a/26577689/12322720

基本上str.contains支持正则表达式,因此可以与or或管道连接

df4[df4.story.str.contains('|'.join(selected_words))]
© www.soinside.com 2019 - 2024. All rights reserved.