使用geopy逆地理编码时触发‘address must not be None’ TypeError问题求助
Hey there! Let's break down why you're hitting this TypeError when scaling up your reverse geocoding—especially since your test sample worked fine. Here are the most likely culprits and fixes:
1. Invalid or Missing Coordinates in Full Dataset
Your test sample probably had clean, valid coordinates, but your full xml_data might have rows with:
- Empty
coordinatesvalues (from missinglat/loncolumns) - Malformed coordinate strings (like
,4.53075or52.06192,instead of a properlat,lonpair) - Coordinate values outside valid ranges (e.g., latitudes >90 or < -90)
Nominatim's reverse() method doesn't handle these edge cases gracefully by returning None—it throws an error instead.
Fix: Clean Your Data First
Add checks to filter out bad coordinates before geocoding:
# Drop rows with missing latitude/longitude values xml_data = xml_data.dropna(subset=['lat', 'lon']) # Keep only properly formatted lat,lon strings (matches decimal numbers, optional space after comma) xml_data = xml_data[xml_data['coordinates'].str.match(r'^-?\d+\.\d+,\s?-?\d+\.\d+$')]
2. Too Aggressive Request Rate
Your min_delay_seconds=0.001 is way below Nominatim's recommended rate limits (they require at least 1 second between requests for free usage). Flooding the service with too many requests too fast can lead to error responses instead of valid None for unaddressable coordinates—this triggers unexpected TypeErrors.
Fix: Slow Down Your Requests
Adjust the rate limiter to respect the service rules:
rgeocode = RateLimiter(locator.reverse, min_delay_seconds=1)
3. Outdated Geopy Version
Older versions of geopy might not handle "no address found" cases as documented, throwing errors instead of returning None.
Fix: Upgrade Geopy
Run this command to get the latest version:
pip install --upgrade geopy
4. Add Exception Handling as a Safety Net
Even with all the above fixes, occasional network blips or odd edge cases can still cause errors. Wrap your geocoding function to catch exceptions and return None manually:
def safe_reverse_geocode(coords): try: return rgeocode(coords) except (TypeError, geopy.exc.GeocoderTimedOut, geopy.exc.GeocoderUnavailable): return None # Apply the safe function instead of direct progress_apply xml_data['address'] = xml_data['coordinates'].progress_apply(safe_reverse_geocode)
Try these steps in order—start with data cleaning, since that's the most common issue when scaling from test samples to full datasets.
内容的提问来源于stack exchange,提问作者Marc Marsidi

