在Pandas数据框中选择任何列包含字符串的行的最简洁方法? [英] Most concise way to select rows where any column contains a string in Pandas dataframe?
问题描述
在Pandas数据框中选择任何列包含字符串的所有行的最简洁方法是什么?
What is the most concise way to select all rows where any column contains a string in a Pandas dataframe?
例如,给定以下数据框,什么是选择其中任何列中的值包含b
的那些行的最佳方法是什么?
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']
})
我对Pandas缺乏经验,到目前为止,我想出的最好的方法是相当笨重的df[df.apply(lambda r: r.str.contains('b').any(), axis=1)]
.有更简单的解决方案吗?
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?
重要的是,我想检查 any 列中的匹配项,而不是特定的列.尽我所知,其他类似问题仅针对单个或一列列表.
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.
推荐答案
这个问题没有得到答案..但是问题本身和评论已经得到了答案,对我来说真的很好.在我看过的其他地方都找不到答案.
所以我只复制粘贴答案给可以发现有用的人.我为不区分大小写的小写添加了case = False
@Reason的解决方案:
到目前为止,我想出的最好的办法是
the best I've come up with so far is the rather cumbersome
这个对我有用.
df[df.apply(lambda r: r.str.contains('b', case=False).any(), axis=1)]
@rbinnun的解决方案:
这个对我来说适用于测试数据集..但是对于某些真实数据集..它返回了unicode错误,如下所示,但我认为通常也是一个很好的解决方案
df[df.apply(lambda row: row.astype(str).str.contains('b', case=False).any(), axis=1)]
照顾非字符串列,nan等.
takes care of non-string columns, nans, etc.
UnicodeEncodeError: 'ascii' codec can't encode character u'\xae' in position 5: ordinal not in range(128)
这篇关于在Pandas数据框中选择任何列包含字符串的行的最简洁方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!