Ignoring NaNs with str.contains

后端 未结 6 495
花落未央
花落未央 2020-11-27 11:23

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:

相关标签:
6条回答
  • 2020-11-27 11:29

    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.

    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.

    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 True or False. I can't tell why making the phrase inside the brackets 'extra boolean' has any effect at all.

    0 讨论(0)
  • 2020-11-27 11:33
    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]
    
    0 讨论(0)
  • 2020-11-27 11:38

    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.

    0 讨论(0)
  • 2020-11-27 11:43

    You can also patern :

    DF[DF.col.str.contains(pat = '(foo)', regex = True) ]
    
    0 讨论(0)
  • 2020-11-27 11:46

    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.replace docs:

    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
    
    0 讨论(0)
  • 2020-11-27 11:47

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

    0 讨论(0)
提交回复
热议问题