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

如何基于条件替换DataFrame列中目标值及其前后相邻值为NaN

解决DataFrame列值及其前后相邻值的替换问题

要实现当列中数值大于45时,将该值及其前、后相邻值都替换为NaN的需求,可以用以下两种实用方法:

方法一:简洁的移位掩码法

利用shift()方法获取相邻元素的条件,构建掩码后批量替换,代码更精简:

import pandas as pd
import numpy as np

# 构建示例DataFrame
df = pd.DataFrame({'col': [10, 12, 25, 60, 32, 26, 23]})

# 创建掩码:当前值>45,或前一个值>45,或后一个值>45
mask = (df['col'] > 45) | (df['col'].shift(1) > 45) | (df['col'].shift(-1) > 45)

# 替换符合掩码条件的值为NaN
df['col'] = df['col'].where(~mask, np.nan)

执行后df['col']的结果为:10, 12, NaN, NaN, NaN, 26, 23,完全匹配需求。

方法二:索引收集法(逻辑更直观)

先定位所有大于45的值的索引,再扩展包含其前后索引,最后批量替换,适合需要明确控制索引范围的场景:

import pandas as pd
import numpy as np

df = pd.DataFrame({'col': [10, 12, 25, 60, 32, 26, 23]})

# 获取所有值>45的索引
target_idx = df[df['col'] > 45].index.tolist()

# 收集需要替换的索引(目标索引+前后相邻索引,处理边界避免越界)
replace_idx = set()
for idx in target_idx:
    replace_idx.add(idx)
    if idx > 0:  # 跳过第一个元素的前索引
        replace_idx.add(idx - 1)
    if idx < len(df)-1:  # 跳过最后一个元素的后索引
        replace_idx.add(idx + 1)

# 替换指定索引的值为NaN
df.loc[replace_idx, 'col'] = np.nan

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 00:21:26