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

如何通过指定Series替换Pandas DataFrame重复索引对应的列值?

解决方法

方法1:loc直接赋值(最简洁,推荐)

这是最符合Pandas规范的写法,自动匹配所有重复索引的行,代码如下:

import pandas as pd

# 示例数据
df = pd.DataFrame(data={'hi':[1, 2, 3, 4, 5, 6, 7]}, index=[1, 1, 1, 2, 2, 3, 4])
exceptions = pd.Series(data=[90, 95], index=[2, 4])

# 核心更新代码
df.loc[exceptions.index, 'hi'] = exceptions

操作原理:loc选中所有索引在exceptions.index中的行时,会自动命中所有重复索引对应的行,赋值时会自动按索引对齐exceptions的取值,不需要额外处理重复索引。
如果不确定exceptions的索引是否全部存在于df中,可以先取索引交集避免意外新增行:

common_idx = df.index.intersection(exceptions.index)
df.loc[common_idx, 'hi'] = exceptions.loc[common_idx]

方法2:reindex对齐+填充(适合多列更新/不修改原数据场景)

如果需要保留原df不修改,或者需要同时更新多列,可以用reindex对齐索引后填充:

# 生成新的DataFrame,不修改原df
new_df = df.copy()
new_df['hi'] = exceptions.reindex(new_df.index).fillna(new_df['hi']).astype(int)

操作原理:reindex会将exceptions按照原df的索引长度扩展,重复索引对应的值会自动复制匹配,不存在的索引位置返回NaN,再用原数据填充NaN即可保留不需要修改的部分。

两种方法都是向量化操作,比循环实现的效率高很多,数据量越大优势越明显。


内容的提问来源于stack exchange,提问作者David Jay Brady

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 16:54:01