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

如何在Pandas中按特定条件向前填充(ffill)指定值

Pandas数据清洗:按条件填充指定值

实现思路

核心逻辑是先筛选出**当前值为5且前一个值属于[30,31,32]**的位置,再用前一个值替换这些位置的5,其余值保持不变。

代码实现

1. 构造示例数据

先模拟你提供的整数索引Series,实际使用时替换为DatetimeIndex即可:

import pandas as pd
import numpy as np

# 示例Series(空值用np.nan表示)
s = pd.Series([np.nan, 5, 3, np.nan, 5, np.nan, 30, 5, 5, 31, 31, np.nan, 5, 5])
# 如果是DatetimeIndex,可替换为:
# idx = pd.date_range(start='2024-01-01', periods=14)
# s = pd.Series([np.nan,5,3,np.nan,5,np.nan,30,5,5,31,31,np.nan,5,5], index=idx)

2. 定义目标值列表与筛选条件

target_values = [30, 31, 32]

# 条件1:当前元素值为5
cond1 = s == 5
# 条件2:前一个元素属于目标值列表
cond2 = s.shift(1).isin(target_values)
# 合并条件:同时满足两个条件的位置
mask = cond1 & cond2

3. 执行替换操作

用前一个元素的值替换满足条件的位置,其余位置保留原值:

result = s.where(~mask, s.shift(1))

4. 查看结果

print(result)

输出结果与期望一致:

0      NaN
1      5.0
2      3.0
3      NaN
4      5.0
5      NaN
6     30.0
7     30.0
8     30.0
9     31.0
10    31.0
11     NaN
12     5.0
13     5.0
dtype: float64

说明

  • shift(1)方法会获取每个位置的前一个元素值,无论索引是整数还是DatetimeIndex(只要索引有序),都能正确取到前一个时间点的数值。
  • where(~mask, s.shift(1))表示:当mask为False时保留原Series的值,当mask为True时用s.shift(1)的值替换。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 17:10:29