Kong
Kong

Reputation: 2422

Pandas get row if column is a substring of string

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)]

Upvotes: 0

Views: 457

Answers (1)

Dani Mesejo
Dani Mesejo

Reputation: 61930

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)

Upvotes: 1

Related Questions