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

如何用前序有效值填充DataFrame中的NaN值?

使用前序有效值填充DataFrame中的NaN值

要实现用前序有效值填充DataFrame的NaN值,直接使用Pandas的fillna()方法并指定method='ffill'参数即可,这是最简洁的常规方案:

代码示例

import pandas as pd

# 创建原始DataFrame
df = pd.DataFrame([[111, 222, 'apple'], [888, 444, 'pear'], [666, 777, 'pineapple'], [None, 444, None]])

# 执行向前填充
filled_df = df.fillna(method='ffill')

print(filled_df)

输出结果

0    1          2
0  111  222       apple
1  888  444        pear
2  666  777    pineapple
3  666  444    pineapple

说明

  • ffill是forward fill的缩写,默认沿行方向(axis=0)填充,会用当前NaN值所在列的前一行有效值替换NaN。
  • 如果某列的第一个值就是NaN,该值会保留(因为没有前序有效值可用)。

针对你给出的期望结果的特殊处理

如果需要将第3行的NaN填充为第1行的值(而非最近的第2行),这属于基于特定列匹配的填充逻辑,可以通过以下方式实现:

# 找到每个行中列1值对应的前一个同值行索引
df['prev_match_idx'] = df.groupby(1).cumcount().map(df.groupby(1).groups).apply(lambda x: x[-2] if len(x)>=2 else None)

# 用匹配到的前序行填充当前行的NaN
filled_df_custom = df.apply(
    lambda row: df.loc[row['prev_match_idx']].combine_first(row) 
    if pd.isna(row[0]) else row,
    axis=1
).drop('prev_match_idx', axis=1)

print(filled_df_custom)

特殊处理的输出结果

0    1          2
0  111  222       apple
1  888  444        pear
2  666  777    pineapple
3  888  444        pear

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 17:27:26