我知道有一个关于在一列中搜索字符串的相关线程(here https://stackoverflow.com/questions/27975069/how-to-filter-rows-containing-a-string-pattern-from-a-pandas-dataframe)但是如何在所有列中使用 pd.Series.str.contains(pattern) 呢?
df = pd.DataFrame({'vals': [1, 2, 3, 4], 'ids': [u'aball', u'bball', u'cnut', u'fball'],
'id2': [u'uball', u'mball', u'pnut', u'zball']})
In [3]: df[df['ids'].str.contains("ball")]
Out[3]:
ids vals
0 aball 1
1 bball 2
3 fball 4
stack
如果您只选择可能有的东西'ball'
哪些列是dtype
object
, 然后你可以stack
将生成的数据帧转换为系列对象。此时你可以执行pandas.Series.str.contains
and unstack
结果返回到数据帧中。
df.select_dtypes(include=[object]).stack().str.contains('ball').unstack()
ids id2
0 True True
1 True True
2 False False
3 True True
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)