Skip to content

Instantly share code, notes, and snippets.

@miere
Created August 10, 2022 12:26
Show Gist options
  • Save miere/89aebf7c752c0b4d8522062226def32c to your computer and use it in GitHub Desktop.
Save miere/89aebf7c752c0b4d8522062226def32c to your computer and use it in GitHub Desktop.

How to find the nearest Airport to a Wind Turbine?

Requirements

Install pandas and geopy on your machine.

pip3 install pandas geopy

How to compute the distance between two geo-locations?

https://stackoverflow.com/a/43211266

How to iterate over all rows of a data-frame?

Note: each row is a reference to the actual dataframe row. You can't modify its content.

https://stackoverflow.com/a/16476974

How to update the actual data-frame and insert a new column?

https://stackoverflow.com/a/29262040

How to export the modified data-frame into a new CSV file?

https://stackoverflow.com/a/16923367

#!/usr/bin/env python3
import pandas as pd
import geopy.distance
def calc_distance(point_a, point_b):
return geopy.distance.geodesic(point_a, point_b).km
# CONSTANTS
TOO_FAR_AWAY_IN_KM = 1000000
# MAIN
airports = pd.read_csv('data/us-airports.csv')
turbines = pd.read_csv('data/us-wind-turbines.csv')
for i, turbine in turbines.iterrows():
print(turbine['case_id'], end='')
turbine_location = (turbine['ylat'], turbine['xlong'])
min_distance = TOO_FAR_AWAY_IN_KM
for j, airport in airports.iterrows():
print('.', end='')
airport_location = (airport['latitude_deg'], airport['longitude_deg'])
distance = calc_distance(airport_location, turbine_location)
if distance <= min_distance:
min_distance = distance
turbines.at[i, 'closest_airport_in_km'] = min_distance
print('\n')
turbines.to_csv('data/us-wind-turbines-updated.csv', sep=',', encoding='utf-8')
print('\nFinished\n')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment