继续我堆栈中的最后一个问题 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/