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

ANZ虚拟实习Pandas处理经纬度数据时转换n/a为float报错求助

问题根因

你当前的判断逻辑仅校验了空字符串""场景,没有覆盖原始Excel中导出的'n/a'空值标识,同时存在两个逻辑问题:

  • 循环中调用replace修改整列数据,执行效率极低
  • 原有判断条件使用or逻辑,只要存在一个非空值就会进入转换流程,只要任意一个坐标值为'n/a'就会触发浮点转换报错
最优解决方案(向量化处理,避免循环)

优先使用pandas向量化操作替代iterrows循环,同时兼容各类空值场景:

import pandas as pd
import numpy as np

# 辅助函数:安全转换float,异常情况返回nan
def safe_float(val):
    val = str(val).strip()
    if val in ('', 'n/a', 'N/A', 'NaN', 'nan'):
        return np.nan
    try:
        return float(val)
    except ValueError:
        return np.nan

# 预处理坐标字段,提前完成格式转换
new_df = pd.DataFrame({
    'CustomerLocation': data.long_lat.apply(lambda x: (safe_float(x[0]), safe_float(x[1]))),
    'MerchantLocation': data.merchant_long_lat.apply(lambda x: (safe_float(x[0]), safe_float(x[1])))
})

# 距离计算函数
def get_distance(row):
    x1, y1 = row['CustomerLocation']
    x2, y2 = row['MerchantLocation']
    # 所有坐标都有效才计算距离
    if pd.notna(x1) and pd.notna(y1) and pd.notna(x2) and pd.notna(y2):
        return haversine((x1, y1), (x2, y2), unit='mi')
    return np.nan

# 批量计算距离,结果存入新列
new_df['distance_mi'] = new_df.apply(get_distance, axis=1)
若需保留原有循环写法的修改方案

仅修改判断逻辑和转换逻辑即可:

new_df=pd.DataFrame({'MerchantLocation':(tuple(num) for num in data.merchant_long_lat), 'CustomerLocation': (tuple(num) for num in data.long_lat)})

for index, row in new_df.iterrows():
    x=row.CustomerLocation
    y=row.MerchantLocation
    # 先处理所有坐标值的空值判断
    x0, x1 = str(x[0]).strip(), str(x[1]).strip()
    y0, y1 = str(y[0]).strip(), str(y[1]).strip()
    # 判断所有坐标都不是空值标识才执行转换
    if all(v not in ('', 'n/a', 'N/A') for v in [x0, x1, y0, y1]):
        print("x:",x)
        # 直接修改当前行值,无需整列replace
        new_df.at[index, "CustomerLocation"] = (float(x0), float(x1))
        new_df.at[index, "MerchantLocation"] = (float(y0), float(y1))
        dist = haversine((float(x0), float(x1)), (float(y0), float(y1)), unit='mi')
        print(dist, "miles")
    else:
        print("存在空坐标值,跳过计算")
说明
  • 方案中兼容了空字符串、n/a、首尾空格等多种常见的空值标识
  • 向量化方案的执行效率远高于逐行循环,适合数据量较大的场景
  • 新增的空值判断逻辑避免了无效值进入浮点转换流程,从根源解决报错问题

内容的提问来源于stack exchange,提问作者Bilal Ahmed

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 20:36:04