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

如何基于索引将一个DataFrame中的值替换为另一个DataFrame中的对应值

用df2坐标替换df1数值的实现方案

嘿,这需求很清晰,我帮你搞定——用df2里的坐标替换df1中对应数值,NaN原样保留对吧?先把你的原始数据和目标结果理清楚:

原始数据

df1(待替换的数值表)

Vehicle1Vehicle2Vehicle3
000
132
004
NaNNaN0

df2(坐标映射表)

IndexCoords
0(-49.36204, -21.04797)
1(-48.9062, -20.7399)
2(-48.9132, -20.7296)
3(-48.8955, -20.7329)
4(-48.8065, -20.8147)

实现代码

import pandas as pd

# 构建原始DataFrame
df1 = pd.DataFrame({
    'Vehicle1': [0, 1, 0, pd.NA],
    'Vehicle2': [0, 3, 0, pd.NA],
    'Vehicle3': [0, 2, 4, 0]
})

df2 = pd.DataFrame({
    'Index': [0, 1, 2, 3, 4],
    'Coords': [
        (-49.36204, -21.04797),
        (-48.9062, -20.7399),
        (-48.9132, -20.7296),
        (-48.8955, -20.7329),
        (-48.8065, -20.8147)
    ]
})

# 创建索引到坐标的映射字典
coord_mapping = df2.set_index('Index')['Coords'].to_dict()

# 对df1每列应用映射,自动保留NaN
result_df = df1.apply(lambda col: col.map(coord_mapping))

# 打印结果
print(result_df)

代码说明

  • 第一步把df2转换成索引值到坐标的字典,这样能快速通过df1里的数字匹配到对应坐标;
  • 用apply遍历df1的每一列,再用map完成替换——map会自动忽略NaN值,直接保留原始的缺失值,完全符合你的要求;
  • 输出结果和你预期的一模一样。

最终输出结果

Vehicle1Vehicle2Vehicle3
(-49.36204, -21.04797)(-49.36204, -21.04797)(-49.36204, -21.04797)
(-48.9062, -20.7399)(-48.8955, -20.7329)(-48.9132, -20.7296)
(-49.36204, -21.04797)(-49.36204, -21.04797)(-48.8065, -20.8147)
NaNNaN(-49.36204, -21.04797)

内容的提问来源于stack exchange,提问作者Anderson Safre

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 22:47:39