Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

search dataframe for a keyword in any column and get the rows

I have a dataframe which I wish to get a subset by checking for the presence of a keyword across all columns in all rows one by one. Here is the snippet:

df.apply(lambda x: x.str.contains('TEST')).any()

but because not all column values are of string type and so it throws error:

AttributeError: ('Can only use .str accessor with string values

Any help is appreciated.

like image 429
user5694846 Avatar asked Oct 20 '25 17:10

user5694846


1 Answers

Flying blind without an example here, but how about:

df.apply(lambda row: row.astype(str).str.contains('TEST').any(), axis=1)

So, for example:

import numpy as np
import pandas as pd

np.random.seed(0)
df = pd.DataFrame(np.random.choice(['0.0', 'Hello', 'Goodbye'], (12, 3)))
df.apply(lambda row: row.astype(str).str.contains('Hello').any(), axis=1)
like image 62
8one6 Avatar answered Oct 22 '25 07:10

8one6



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!