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

如何用Pandas DataFrame中上方最近的已填充值填补缺失项?

解决方案

首先构造你提供的原始DataFrame:

import pandas as pd

df = pd.DataFrame(
    {'col1': ['"a"', None, '"b"', None, None]},
    index=[1, 2, 3, 4, 5]
)

使用pandas的**前向填充(forward fill)**方法即可实现需求,直接用fillna指定method='ffill':

# 填充缺失值
df['col1'] = df['col1'].fillna(method='ffill')

处理后的DataFrame如下:

indexcol1
1"a"
2"a"
3"b"
4"b"
5"b"

这种方法会自动将每一个缺失值替换为该列中最近的前一个非缺失值,完全匹配你想要的结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 21:54:58