What is the most concise way to select all rows where any column contains a string in a Pandas dataframe?
For example, given the following dataframe what is the best way to select those rows where the value in any column contains a b
?
df = pd.DataFrame({
'x': ['foo', 'foo', 'bar'],
'y': ['foo', 'foo', 'foo'],
'z': ['foo', 'baz', 'foo']
})
I'm inexperienced with Pandas and the best I've come up with so far is the rather cumbersome df[df.apply(lambda r: r.str.contains('b').any(), axis=1)]
. Is there a simpler solution?
Critically, I want to check for a match in any columns, not a particular column. Other similar questions, as best I can tell, only address a single or list of columns.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…