1

I have some list values I want to check against another list of conditions.

For example, the condition list I want to check against is ['042', '043', '044']. I want to return True as long as the initial substring contains any of these values.

For example, ['04233'], ['042'] or ['042', '011'] should return True. But for ['11042'] or ['13044'], even though it contains the check conditions as substring, because they are not the initial characters, they should return False.

My code is as follows:

import pandas as pd

df = pd.DataFrame(['152042']) #'04211'
df.columns=['test_list']

cond_list = ['042', '043', '044']

print (df['test_list'].str.contains('|'.join(cond_list)).any())

# Return True, but False is desired.

I am not sure how I can incorporating both substring checking and at the same time ensuring the subtrings occur as leading characters.

4
  • Use ^ to assert a match at the start of a string Commented Dec 11, 2018 at 19:47
  • change contains to startswith Commented Dec 11, 2018 at 19:49
  • 1
    @user3483203 let me write it to an answer . Commented Dec 11, 2018 at 19:51
  • xion.io/post/code/python-startswith-tuple.html Commented Dec 11, 2018 at 19:54

2 Answers 2

3

Using startswith, notice it accpet tuple not list

df['test_list'].str.startswith(tuple(cond_list))
Out[47]: 
0    False
Name: test_list, dtype: bool
Sign up to request clarification or add additional context in comments.

Comments

2

You've got the general idea, you just need to add an assertion to match at the beginning of your string, using a ^ character.

rgx = '^({})'.format('|'.join(cond_list))
# '^(042|043|044)'

df['test_list'].str.contains(rgx).any()

False

2 Comments

I got a warning "UserWarning: This pattern has match groups. To actually get the groups, use str.extract. 1 if row[var_name_list].str.contains(rgx).any() else 0, axis=1)", is this not a concern?
Not a concern, if the warning bothers you, you can convert the matching group to be non-capturing: rgx = '^(?:{})'.format('|'.join(cond_list))

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.