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

如何基于另一DataFrame的ID坐标映射替换现有DataFrame的ID列为坐标列

实现方法

可以通过pandas的映射或者关联匹配实现需求,以下提供两种常用方案:

方案1:使用map映射(写法更简洁)

先基于df1生成坐标映射字典,直接为df2生成新列即可:

import pandas as pd

# 生成坐标映射表
x_map = df1.set_index('IDLocation')['x-coord'].to_dict()
y_map = df1.set_index('IDLocation')['y-coord'].to_dict()

# 生成新列
df2['Px-coord'] = df2['PIDLocation'].map(x_map)
df2['Py-coord'] = df2['PIDLocation'].map(y_map)
df2['Dx-coord'] = df2['DIDLocation'].map(x_map)
df2['Dy-coord'] = df2['DIDLocation'].map(y_map)

# 可选:删除原始的ID列
df2 = df2.drop(columns=['PIDLocation', 'DIDLocation'])

方案2:使用merge关联(适合复杂关联场景)

通过两次关联匹配获取对应坐标,重命名列后删除冗余字段:

res = df2.merge(df1, left_on='PIDLocation', right_on='IDLocation', how='left')\
         .rename(columns={'x-coord': 'Px-coord', 'y-coord': 'Py-coord'})\
         .merge(df1, left_on='DIDLocation', right_on='IDLocation', how='left')\
         .rename(columns={'x-coord': 'Dx-coord', 'y-coord': 'Dy-coord'})\
         .drop(columns=['PIDLocation', 'DIDLocation', 'IDLocation_x', 'IDLocation_y'])

两种方案默认你的df1中已经覆盖了df2所有的PIDLocation、DIDLocation取值,不需要额外处理缺失值。

内容的提问来源于stack exchange,提问作者Nada.M

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 07:06:08