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

Pandas中如何按列条件在值为NaN时获取前序行有效值?

时序DataFrame条件取最近有效值实现

核心需求

  • 处理带DatetimeIndex的时序类型pandas DataFrame
  • 取值规则:当col1列值为1时,获取对应行col2、col3的最近有效值
  • 给定样例的期望输出:col2:7、col3:11

初始样例代码

import pandas as pd
import numpy as np

d = {'col1': [0,0,1,0,0], 'col2' : [0,7,'N/A',9,10], 'col3': [11,'N/A','N/A',14,15]}
index = pd.DatetimeIndex(['2014-07-04', '2014-08-04', '2015-07-04', '2015-08-04', '2015-09-04'])
d = pd.DataFrame(data = d, index = index)
d = d.replace('N/A', np.nan)

样例中col1=1的行(2015-07-04)本身col2、col3均为空值,需要沿时间轴取最近的非空值,符合时序数据取已发生最近观测值的通用逻辑。

实现代码

利用pandas的前向填充ffill(),沿时间轴从上到下(即从早到晚的时间顺序)填充空值,空值会自动取该列之前最近的非空值,之后直接筛选col1=1的行提取值即可:

# 对col2、col3沿时间顺序做前向填充
d[['col2', 'col3']] = d[['col2', 'col3']].ffill()

# 提取col1=1对应的目标值
target = d[d['col1'] == 1].iloc[0]
print(f"col2:{int(target['col2'])}、col3:{int(target['col3'])}")

运行后输出结果和预期完全一致:col2:7、col3:11

如果业务场景需要同时考虑目标行之后的最近值,可以改用双向填充d[['col2', 'col3']] = d[['col2', 'col3']].ffill().bfill(),针对当前样例前向填充即可满足要求。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 12:57:14