0

How can I check if all multiple strings existing in another string?

Then assign the result to a new column named "value".

Example of the dataframe:

sub_strings string value
["the sun", "rising up"] "the sun is rising up." True
["go home", "tomorow"] "I will go home." False

My code is:

if all(x in df["string"] for x in df["sub_strings"]):
    df['value'] = True
else:
    df['value'] = False

Could you please help me? Thank you in advance.

1 Answer 1

1

this code snippet should do your work:

df = pd.DataFrame({'sub_strings': [["the sun", "rising up"], ["go home", "tomorow"]], 'string': ["the sun is rising up.", "I will go home."]})
df.head()
            sub_strings                 string
0  [the sun, rising up]  the sun is rising up.
1    [go home, tomorow]        I will go home.
df['value'] = df.apply(lambda x: all([val in x.string for val in x.sub_strings]), axis=1)
df.head()
            sub_strings                 string  value
0  [the sun, rising up]  the sun is rising up.   True
1    [go home, tomorow]        I will go home.  False
Sign up to request clarification or add additional context in comments.

2 Comments

Suppose you have a large dataset (1000+ ids), have you tested the speed?
@XxJames07- No I did not check the speed on 1000+ ids, need to create sample data for that. But I suppose Meeow(author) can further optimize the solution.

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.