From a26a02e04d2d0a5cdb5ec5c5f38ec672096206b0 Mon Sep 17 00:00:00 2001 From: Tom Russell Date: Mon, 13 Nov 2023 17:15:56 +0000 Subject: [PATCH] Use iloc in nearest - STRTree returns array index Closes #49 --- src/snkit/network.py | 2 +- tests/test_init.py | 28 ++++++++++++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/src/snkit/network.py b/src/snkit/network.py index 491dab8..7154f63 100644 --- a/src/snkit/network.py +++ b/src/snkit/network.py @@ -705,7 +705,7 @@ def nearest(geom: Geometry, gdf: GeoDataFrame) -> "pandas.Series[Any]": """Find the element of a GeoDataFrame nearest a shapely geometry""" try: match_idx = gdf.sindex.nearest(geom, return_all=False)[1][0] - nearest_geom: "pandas.Series[Any]" = gdf.loc[match_idx] + nearest_geom: "pandas.Series[Any]" = gdf.iloc[match_idx] return nearest_geom except TypeError: diff --git a/tests/test_init.py b/tests/test_init.py index 3ae6f77..827bba7 100644 --- a/tests/test_init.py +++ b/tests/test_init.py @@ -846,3 +846,31 @@ def test_matching_gdf_from_geoms(edge_only): gdf["b"] = "abc" actual = snkit.network.matching_gdf_from_geoms(gdf, geoms) assert_frame_equal(actual, expected) + + +def test_nearest(): + a = Point((0, 0)) + b = Point((0, 2)) + c = Point((0, 1)) + d = Point((1, 1)) + ab = LineString([a, b]) + cd = LineString([c, d]) + gdf = GeoDataFrame(geometry=[ab, cd]) + + # default RangeIndex + actual = snkit.network.nearest(Point(0.1, -0.1), gdf) + assert actual.geometry == LineString([Point(0, 0), Point(0, 2)]) + + # set integer index, not running from 0..n + gdf["edge_id"] = [1, 4] + gdf.set_index("edge_id", inplace=True) + actual = snkit.network.nearest(Point(1.0, 0.9), gdf) + assert actual.name == 4 + assert actual.geometry == LineString([Point(0, 1), Point(1, 1)]) + + # set a non-integer index + gdf["edge_id"] = ["ab", "cd"] + gdf.set_index("edge_id", inplace=True) + actual = snkit.network.nearest(Point(1.1, 1.1), gdf) + assert actual.name == "cd" + assert actual.geometry == LineString([Point(0, 1), Point(1, 1)])