geopy坐标提取遇问题:astype(str)丢坐标,extract返回NaN
Ah, I get it—you're overcomplicating things by trying to parse strings when geopy gives you structured objects with direct access to coordinates. Let's break down the problem and fix this properly:
The Root Issue
When you run geolocator.geocode(), it returns a Location object (not a raw string). These objects have built-in latitude and longitude attributes—no regex or string conversion needed! The NaNs and truncated strings you're seeing happen because:
- Pandas truncates long string representations of Location objects (hence the
Ashaiman, Gr...in your sample) - Regex can't reliably parse these partial/truncated strings
- Converting the entire object to string loses the structured data you actually need
Fix 1: Extract Coordinates Directly from Location Objects
Use apply() to access the latitude and longitude attributes for each row. We'll add a check for None (in case some addresses fail to geocode) to avoid errors:
# Extract latitude and longitude from the Location objects data['g_latitude'] = data['geocode_result'].apply(lambda x: x.latitude if x is not None else None) data['g_longitude'] = data['geocode_result'].apply(lambda x: x.longitude if x is not None else None)
Fix 2: Extract Coordinates During Geocoding (More Efficient)
If you don't need to keep the full Location objects (with address details), you can extract coordinates directly while geocoding to save memory:
# Initialize empty lists for coordinates latitudes = [] longitudes = [] for address in data['ghana_city']: location = geolocator.geocode(address, timeout=60) if location: latitudes.append(location.latitude) longitudes.append(location.longitude) else: # Handle addresses that couldn't be geocoded latitudes.append(None) longitudes.append(None) # Add the coordinates to your DataFrame data['g_latitude'] = latitudes data['g_longitude'] = longitudes
Why This Works Better
- No messy string parsing or regex hacks
- Avoids truncated strings and NaN results from failed regex matches
- Directly uses the structured data geopy provides, which is far more reliable
- Handles edge cases where addresses don't return a location gracefully
内容的提问来源于stack exchange,提问作者SuperSecretAndNotSafeFromWork

