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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With