start geopandas exercise

This commit is contained in:
Philip 2025-07-17 13:01:44 +02:00
parent bcc78638df
commit 4e941467eb

View File

@ -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)