python - 从 pandas 的数据框列中搜索字符串模式

标签 python regex pandas

继续我堆栈中的最后一个问题 searching matching string pattern from dataframe column in python pandas

假设我有一个数据框

 name         genre
 satya      |ACTION|DRAMA|IC|
 satya      |COMEDY|DRAMA|SOCIAL|MUSIC|
 abc        |DRAMA|ACTION|BIOPIC|
 xyz        |ACTION||ROMANCE|DARMA|
 def        |ACTION|SPORT|COMEDY|IC|
 ghj        |IC|ACTIONDRAMA|NOACTION|

根据我上一个问题的答案,如果独立存在于流派列中并且不作为任何其他流派字符串值(MUSIC 或 BIOPIC)的一部分,我可以搜索任何一种流派(例如 IC)。

现在我想查找 ACTION 和 DRAMA 是否都出现在流派列中,但不一定按特定顺序,并且不是字符串的一部分,而是单独出现。

所以我需要输出行[1,3,4]中的行

 name         genre
 satya      |ACTION|DRAMA|IC|   # both adjacently present
 #row 2 will not come           # as only DRAMA present not ACTION
 abc        |DRAMA|ACTION|BIOPIC|   ### both adjacently present in diff. order
 xyz        |ACTION||ROMANCE|DARMA|   ### both present not adjacent
 ##row  5 should not present as DRAMA is not here
 ## row 6 should not come as both are not present individually(but present as one string part)

我尝试过类似的方法

 x = df[df['gen'].str.contains('\|ACTION\|DRAMA\|')]
 ### got only Row  1 (ACTION and DRAMA in adjacent and in order ACTION->DRAMA)

请有人建议在这里可以遵循/添加什么,以便我可以在这里得到我需要的东西。

最佳答案

我认为你可以使用str.contains有两个条件 AND - &:

print df
    name                        genre
0  satya            |ACTION|DRAMA|IC|
1  satya  |COMEDY|DRAMA|SOCIAL|MUSIC|
2    abc        |DRAMA|ACTION|BIOPIC|
3    xyz      |ACTION||ROMANCE|DRAMA|
4    def     |ACTION|SPORT|COMEDY|IC|
5    ghj    |IC|ACTIONDRAMA|NOACTION|

print df['genre'].str.contains('\|ACTION\|') & df['genre'].str.contains('\|DRAMA\|') 
0     True
1    False
2     True
3     True
4    False
5    False
Name: genre, dtype: bool

print df[ df['genre'].str.contains('\|ACTION\|') & df['genre'].str.contains('\|DRAMA\|') ]
    name                    genre
0  satya        |ACTION|DRAMA|IC|
2    abc    |DRAMA|ACTION|BIOPIC|
3    xyz  |ACTION||ROMANCE|DRAMA|

关于python - 从 pandas 的数据框列中搜索字符串模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36833491/

相关文章:

r - 优化 R 中的正则表达式以进行子字符串提取

python - 服务器无法恢复事务。描述 :9800000002. (3971) (SQLEndTran)')

python - 如何检查 Pandas 行是否包含空集

python - 如何将颜色条以 seaborn 热图的定义值居中?

javascript - django中刷新传单 map

python - 如何使用 wxPython 中的 AddSubclassFactory?

javascript - 无效的正则表达式`Javascript

regex - 空正则表达式文字 (!!//) 的 Double-not 为 false,这是解析错误吗?

python - 如何使用单个命令 [Python - Pandas] 获取所有列的数据类型?

java - 无法将数据从 Java 客户端发送到 Python 服务器