0

I can do the following if I want to extract rows whose column "A" contains the substring "hello".

df[df['A'].str.contains("hello")]

How can I select rows whose column is the substring for another word? e.g.

df["hello".contains(df['A'].str)]

Here's an example dataframe

df = pd.DataFrame.from_dict({"A":["hel"]})
df["hello".contains(df['A'].str)]
3

1 Answer 1

1

IIUC, you could apply str.find:

import pandas as pd

df = pd.DataFrame(['hell', 'world', 'hello'], columns=['A'])
res = df[df['A'].apply("hello".find).ne(-1)]
print(res)

Output

       A
0   hell
2  hello

As an alternative use __contains__

res = df[df['A'].apply("hello".__contains__)]
print(res)

Output

       A
0   hell
2  hello

Or simply:

res = df[df['A'].apply(lambda x: x in "hello")]
print(res)
Sign up to request clarification or add additional context in comments.

1 Comment

thank you! the lambda method is the most intuitive one

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.