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

Python中两个DataFrame区域编号匹配替换为经纬度及报错解决

报错原因

你遇到的ValueError: Replacement lists must match in length. Expecting 260 got 265 核心原因是替换操作返回的结果长度和原表待替换列的长度不一致,常见诱因有三类:

  • 区域坐标表存在重复的区域编号,单个编号匹配到多条经纬度记录,导致结果行数膨胀
  • 尝试直接将单列的位置编号替换为经度+纬度两个数值,单列260行的结构无法容纳两倍长度的内容
  • 行程表的位置编号存在坐标表里未收录的异常值,匹配逻辑返回了额外的占位值

你提供的两张表示例如下:
第一个DataFrame示例
第二个DataFrame示例

正确实现方案

不要直接替换原位置列,新增4列分别存储起点、终点的经纬度,示例代码如下:

import pandas as pd

# 请替换下方变量名为你实际的表名、列名
trip_df = # 你的第一个行程表
loc_df = # 你的第二个区域坐标表,假设区域编号列名为location_id,经度列Longitude,纬度列Latitude

# 第一步:先对坐标表去重,确保一个区域编号仅对应一组经纬度
loc_df = loc_df.drop_duplicates(subset='location_id', keep='first')

# 第二步:构造经纬度映射字典
lon_map = loc_df.set_index('location_id')['Longitude'].to_dict()
lat_map = loc_df.set_index('location_id')['Latitude'].to_dict()

# 第三步:匹配起点经纬度
trip_df['pu_lon'] = trip_df['PuLocation'].map(lon_map)
trip_df['pu_lat'] = trip_df['PuLocation'].map(lat_map)

# 第四步:匹配终点经纬度
trip_df['do_lon'] = trip_df['DoLocation'].map(lon_map)
trip_df['do_lat'] = trip_df['DoLocation'].map(lat_map)

# 可选:删除原有的位置编号列
trip_df = trip_df.drop(columns=['PuLocation', 'DoLocation'])

问题排查代码

如果依然存在问题,可通过以下代码定位异常值:

# 查看行程表中未被坐标表收录的起点编号
pu_missing = trip_df[~trip_df['PuLocation'].isin(loc_df['location_id'])]['PuLocation'].unique()
print(f'未收录的起点编号:{pu_missing}')

# 查看行程表中未被坐标表收录的终点编号
do_missing = trip_df[~trip_df['DoLocation'].isin(loc_df['location_id'])]['DoLocation'].unique()
print(f'未收录的终点编号:{do_missing}')

# 查看坐标表中重复的区域编号
dup_loc = loc_df[loc_df.duplicated(subset='location_id', keep=False)]['location_id'].unique()
print(f'重复的区域编号:{dup_loc}')

内容的提问来源于stack exchange,提问作者Ohood Alsohaime

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 09:45:03