You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现get_coords函数:从地址字符串提取经纬度并处理缺失值

Solution for get_coords() Function

Got it, let's build a reliable get_coords() function that meets your requirements. Here's a complete implementation with explanations for edge cases:

Complete Code

import re
import numpy as np

def get_coords(item):
    # Regular expression to match latitude and longitude in (lat, lon) format
    # Handles optional spaces after the comma, and positive/negative values
    coord_regex = r'\((-?\d+\.\d+),\s*(-?\d+\.\d+)\)'
    match_result = re.search(coord_regex, item)
    
    if match_result:
        # Extract and convert the captured groups to floats
        latitude = float(match_result.group(1))
        longitude = float(match_result.group(2))
        return [latitude, longitude]
    else:
        # Return NaN values for both coordinates when missing
        return [np.nan, np.nan]

How It Works

Let's break down the logic step by step:

  • Regex Pattern: The pattern r'\((-?\d+\.\d+),\s*(-?\d+\.\d+)\)' is tailored to target the coordinate pair wrapped in parentheses:
    • \( and \) match the literal opening and closing parentheses
    • (-?\d+\.\d+) captures a floating-point number (supports negative values for southern latitudes or western longitudes)
    • \s* accounts for any number of spaces between the comma and longitude, handling inconsistent formatting like (36.787,-76.157) or (36.787, -76.157)
  • Matching & Extraction: re.search() scans the input string for the pattern. If found, we pull the two captured groups, convert them to floats, and return as a list.
  • Missing Coordinates: If no valid coordinate pair is found, we return a list containing two numpy.nan values to keep the return type consistent (always a list of two elements).

Test Examples

Example Input (Valid Coordinates)

sample_text = '1533 Bridle Creek Blvd\nVirginia Beach, VA 23464-7907\n(36.787392, -76.15761)'
print(get_coords(sample_text))  # Output: [36.787392, -76.15761]

Input with Missing Coordinates

missing_coords_text = '456 Oak Ave\nChicago, IL 60601'
print(get_coords(missing_coords_text))  # Output: [nan, nan]

Edge Case: No Spaces After Comma

no_space_text = '789 Pine Rd\nMiami, FL 33101\n(25.761681,-80.191788)'
print(get_coords(no_space_text))  # Output: [25.761681, -80.191788]

内容的提问来源于stack exchange,提问作者Garrus HD

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:42:13