忽略带有str.contains的NaN [英] Ignoring NaNs with str.contains

查看:176
本文介绍了忽略带有str.contains的NaN的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想查找包含字符串的行,如下所示:

I want to find rows that contain a string, like so:

DF[DF.col.str.contains("foo")]

但是,这失败了,因为某些元素是NaN:

However, this fails because some elements are NaN:

ValueError:无法使用包含NA/NaN值的向量建立索引

ValueError: cannot index with vector containing NA / NaN values

所以我求助于迷惑的

DF[DF.col.notnull()][DF.col.dropna().str.contains("foo")]

有更好的方法吗?

推荐答案

对此有一个标记:

In [11]: df = pd.DataFrame([["foo1"], ["foo2"], ["bar"], [np.nan]], columns=['a'])

In [12]: df.a.str.contains("foo")
Out[12]:
0     True
1     True
2    False
3      NaN
Name: a, dtype: object

In [13]: df.a.str.contains("foo", na=False)
Out[13]:
0     True
1     True
2    False
3    False
Name: a, dtype: bool

请参见 str.replace 文档:

See the str.replace docs:

na:默认NaN,填充缺失值的值.

na : default NaN, fill value for missing values.


因此您可以执行以下操作:


So you can do the following:

In [21]: df.loc[df.a.str.contains("foo", na=False)]
Out[21]:
      a
0  foo1
1  foo2

这篇关于忽略带有str.contains的NaN的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆