3

I am looking to find if two different strings are present in a row of a dataframe.

For example, I currently have this code which provides answers with item a OR b.

items=('a|b')
df1 = train[train['antecedents'].str.contains(items,flags=re.IGNORECASE, regex=True)]

As helpful as this is, I am looking to find all rows that have item a AND b.

Because I can't use multiple str.contains (as the number of items aren't specified until inputted into the items variable), I don't know how to incorporate the '&' into str.contains (I've tried and it doesn't work).

Is there possibly a different way to incorporate the '&' ?

2
  • 1
    Probably, the easiest way would be to create a function for this. Iterate over all the elements you are looking for, and continue while you find them until the end. Commented Dec 26, 2018 at 8:42
  • What about adding a column that concatenates all the text in the row, just for purposes of searching? Commented Dec 26, 2018 at 8:44

1 Answer 1

5

Just combine 2 conditions with & operator:

df1 = train[(train.antecedents.str.contains('a', case=False)) \
            & (train.antecedents.str.contains('b', case=False))]

Regex alternative:

df1 = train[train.antecedents.str.contains('a.*b|b.*a', regex=True, flags=re.I)]
  • a.*b|b.*a - regex alternation group, ensures that the input string contains both a and b in any position (relative to one another).
Sign up to request clarification or add additional context in comments.

2 Comments

Hey, is there a way to a variable list be used in the str.contains ? (like the items variables above) for example, the code still works if there is only one str.contain, but can have any number of items each time the code has run.
@FI_2018, create a function for that purpose so it accepts search strings like my_func('a', 'b', 'c'). Then use it wherever you need.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.