Python 使用 str.contains 忽略 NaN

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28311655/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 03:05:06  来源:igfitidea点击:

Ignoring NaNs with str.contains

pythonpandas

提问by Emre

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

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

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

However, this fails because some elements are NaN:

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

ValueError: cannot index with vector containing NA / NaN values

ValueError: 无法索引包含 NA / NaN 值的向量

So I resort to the obfuscated

所以我求助于混淆

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

Is there a better way?

有没有更好的办法?

采纳答案by Andy Hayden

There's a flag for that:

有一个标志:

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

See the str.replacedocs:

查看str.replace文档:

na : default NaN, fill value for missing values.

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



So you can do the following:

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

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

回答by Faheem Alvi

import folium
import pandas

data= pandas.read_csv("maps.txt")

lat = list(data["latitude"])
lon = list(data["longitude"])

map= folium.Map(location=[31.5204, 74.3587], zoom_start=6, tiles="Mapbox Bright")

fg = folium.FeatureGroup(name="My Map")

for lt, ln in zip(lat, lon):
c1 = fg.add_child(folium.Marker(location=[lt, ln], popup="Hi i am a Country",icon=folium.Icon(color='green')))

child = fg.add_child(folium.Marker(location=[31.5204, 74.5387], popup="Welcome to Lahore", icon= folium.Icon(color='green')))

map.add_child(fg)

map.save("Lahore.html")


Traceback (most recent call last):
  File "C:\Users\Ryan\AppData\Local\Programs\Python\Python36-32\check2.py", line 14, in <module>
    c1 = fg.add_child(folium.Marker(location=[lt, ln], popup="Hi i am a Country",icon=folium.Icon(color='green')))
  File "C:\Users\Ryan\AppData\Local\Programs\Python\Python36-32\lib\site-packages\folium\map.py", line 647, in __init__
    self.location = _validate_coordinates(location)
  File "C:\Users\Ryan\AppData\Local\Programs\Python\Python36-32\lib\site-packages\folium\utilities.py", line 48, in _validate_coordinates
    'got:\n{!r}'.format(coordinates))
ValueError: Location values cannot contain NaNs, got:
[nan, nan]

回答by Harry_pb

In addition to the above answers, I would say for columns having no single word name, you may use:-

除了上述答案,我想说对于没有单个单词名称的列,您可以使用:-

df[df['Product ID'].str.contains("foo") == True]

Hope this helps.

希望这可以帮助。

回答by Nate Taylor

I'm not 100% on why (actually came here to search for the answer), but this also works, and doesn't require replacing all nan values.

我不是 100% 为什么(实际上是来这里寻找答案),但这也有效,并且不需要替换所有 nan 值。

import pandas as pd
import numpy as np

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

newdf = df.loc[df['a'].str.contains('foo') == True]

Works with or without .loc.

有或没有.loc.

I have no idea why this works, as I understand it when you're indexing with brackets pandas evaluates whatever's inside the bracket as either Trueor False. I can't tell why making the phrase inside the brackets 'extra boolean' has any effect at all.

我不知道为什么会这样,正如我所理解的,当您使用括号进行索引时,pandas 会将括号内的任何内容评估为Trueor 或False。我不知道为什么将括号内的短语设为“额外布尔值”会产生任何影响。

回答by Aliakbar Hosseinzadeh

You can also patern :

你也可以模式:

DF[DF.col.str.contains(pat = '(foo)', regex = True) ]