Search code examples
pythonpython-3.xpandascartopy

Python: Drop Pandas row if function returns false, utilizing is _land check through Cartopy


I want to drop a row based on whether the function returns true or not, the function checks whether the latitude and longitude values are on land. I want to drop rows where the lat/long returns false.

This is what I have so far but im stuck:

def LAND_SHAPE_READER():
    land_shp_fname = shpreader.natural_earth(resolution='10m',
                                             category='physical', 
name='land')

    land_geom = unary_union(list(shpreader.Reader(land_shp_fname).geometries()))
    land = prep(land_geom)

def IS_LAND(x, y):
    return land.contains(sgeom.Point(x, y))

def MAP_PLOT_CHECK():
    if IS_LAND(df['Longitude'], df['Latitude']):
        return
    else:  
        #drop row here

Solution

  • I think the safest way to do this would be to create a new column that stores your IS_LAND value.

    # Apply this function to every row, where x is the row
    # Save the True/False return value as a column
    df['IS_LAND_RETURN'] = df.apply(lambda x: IS_LAND(x['Longitude'], x['Latitude']), axis=1)
    

    After that filtering is trivial:

    # Select df rows where IS_LAND_RETURN is true
    land_only = df[df['IS_LAND_RETURN']]