How to find data of a city based on it’s longitude and latitude from the worldcities?

  Data, Pandas, Python

The following example is to find latitude and longitude of a city from the data worldcities (https://datahub.io/core/world-cities) and then based on the latitude and longitude to slice data from era5 data of this city. It also can be used to find data from other source spatial data.

Answer other questions:

  • How to read netcdf file with xarray?
  • How to slice subdomain (time, longitude, latitude) data from xarray data?
import pandas as pd
import xarray as xr

#read the source data
cities=pd.read_csv('worldcities.csv')
# cities in Canada
ca_cities=cities[cities.country=="Canada"]
ca_cities=ca_cities.sort_values('population',ascending=False)
ca_cities=ca_cities.head(500)
ca_cities

#round longitude and latitude to 0.1 for slicing 0.1degree netcdf data
ca_cities['lat']=ca_cities['lat'].round(decimals=1)
ca_cities['lng']=ca_cities['lng'].round(decimals=1)+360
ca_cities

fn = 'reanalysis-era5-land-monthly-means.nc'
ds=xr.open_dataset(fn)
#slice data at (236.9,49.2)
air_city = ds.tasAdjust.sel(time=slice('1960-01-01','1960-12-31'),lon=slice(236.85,236.95),lat=slice(49.15,49.25))-273.15