From 4e941467ebf0180c4afdec40786090d3ffea5f91 Mon Sep 17 00:00:00 2001 From: Philip Date: Thu, 17 Jul 2025 13:01:44 +0200 Subject: [PATCH] start geopandas exercise --- src/T20_Geopandas_joining.py | 55 ++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 src/T20_Geopandas_joining.py diff --git a/src/T20_Geopandas_joining.py b/src/T20_Geopandas_joining.py new file mode 100644 index 0000000..7dc8b34 --- /dev/null +++ b/src/T20_Geopandas_joining.py @@ -0,0 +1,55 @@ +import geopandas as gpd +import matplotlib.pyplot as plt + + +world = gpd.read_file("../data/110m_cultural.zip", layer="ne_110m_admin_0_countries") +cities = gpd.read_file("../data/110m_cultural.zip", + layer="ne_110m_populated_places") + + +def find_neighbouring_countries(df, country_name): + target = df[df["NAME"] == country_name] + + if len(target) == 0: + print(f"{country_name} not found") + return gpd.GeoDataFrame() + + # sjoin spatial-join + neighbours = gpd.sjoin(target, df, how="inner", predicate="touches") + return neighbours[["NAME_right", "CONTINENT_right", "geometry"]] + +def get_close_cities(df, city_name): + target = df[df["NAMEASCII"] == city_name] + + if len(target) == 0: + print(f"{city_name} not found") + return gpd.GeoDataFrame() + + # sjoin spatial-join + neighbours = gpd.sjoin_nearest(target, df, max_distance=10e12) + return neighbours + + +#intersects +#contains +#within +#touches +#crosses +#overlaps +german_neighbours = find_neighbouring_countries(world, "Germany") +print(german_neighbours[["NAME_right", "CONTINENT_right"]]) +print(len(german_neighbours)) +print("-"*100) +w2 = world.to_crs("EPSG:3857") +c2 = cities.to_crs("EPSG:3857") +print(list(c2.columns)) +german_neighbours = get_close_cities(c2, "Paris") +print(len(german_neighbours)) +print(german_neighbours) + +w2.plot(column="CONTINENT", legend=True) +plt.show() + + +# 1) get_cities_in_country (sjoin) +# 2) get_cities_in_countries (concat) \ No newline at end of file