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

如何将DataFrame最后索引行的数值按指定字典映射替换

实现方案

你可以通过pandas的行索引定位直接赋值实现需求,以下是可运行的完整代码:

import pandas as pd

# 构造初始DataFrame
d = {'col1': [11, 12, 13], 'col2': [14, 15, 16]}
df = pd.DataFrame(d)
# 待赋值的映射字典
dict_ = {'col1': '8', 'col2': '9'}

# 通用方案:用iloc定位最后一行,不受索引值影响
# 若需要和其他行保持整数类型,可先转换字典值:dict_ = {k:int(v) for k,v in dict_.items()}
df.iloc[-1] = pd.Series(dict_)

# 输出验证
print(df)

其他可选方案

如果你确定最后一行的索引固定为2,也可以直接用loc赋值,写法更简单:

df.loc[2] = dict_

运行后输出结果和要求完全一致:

col1  col2
0    11    14
1    12    15
2     8     9

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 13:27:02