我正在使用Pandas
中的快速、矢量化的str.contains
方法来检查数据帧中的每一行是否至少包含一个来自我的list_word
的单词。在
list_words='foo ber haa'
df = pd.DataFrame({'A' : ['foo foor', 'bar bar', 'foo hoo', 'bar haa',
'foo bar', 'bar bur', 'foo fer', 'foo for']})
df
Out[113]:
A
0 foo foor
1 bar bar
2 foo hoo
3 bar haa
4 foo bar
5 bar bur
6 foo fer
7 foo for
df.A.str.contains("|".join(list_words.split(" ")))
Out[114]:
0 True
1 False
2 True
3 True
4 True
5 False
6 True
7 True
Name: A, dtype: bool
问题是:如何检查每一行是否至少包含列表中的两个单词?。在
我想坚持使用str.contains
,因为它比其他python字符串匹配算法快得多。在
您可以将^{} 与
list comprehension
一起使用:计时:
^{pr2}$假设
ber
应该是bar
,那么您可以将.apply
与集合一起使用-注意这会整词-而不是子串(例如,foo
在foor
中找不到)。。。在给你:
^{pr2}$我是熊猫(和python一般来说)的初学者,所以我想把它当作一种挑战,而不是获得赞成票:)。只是使用了我知道的技术,但它们比其他人提出的要慢得多。在
我会检查其他人提出的技术:)
相关问题 更多 >
编程相关推荐