fillna方法中method='pad'与method='ffill'的差异及优选性探讨
pad vs ffill in pandas' fillna() Great question—you’re totally right to notice they seem identical, because they actually are fully equivalent! Let’s break this down clearly:
- Core Relationship:
padis just an alias forffillin pandas. That means under the hood, callingdf.fillna(method='pad')runs exactly the same code asdf.fillna(method='ffill'). - Why Two Names?: It’s mostly about naming conventions and compatibility.
ffillis short for forward fill, which makes its behavior immediately obvious (fill missing values with the previous non-null entry).padleans into the literal "pad" (fill in gaps) terminology, which some developers might prefer for brevity. - Behavior Check: Here’s a quick snippet to confirm they produce identical results:
import pandas as pd import numpy as np df = pd.DataFrame({'values': [2, np.nan, 5, np.nan, 9]}) # Both lines will fill NaNs with 2 and 5 respectively result_pad = df.fillna(method='pad') result_ffill = df.fillna(method='ffill') print(result_pad.equals(result_ffill)) # Output: True
Preferred Method?
While there’s no functional difference, ffill is generally the more popular choice in modern pandas code. Its explicit "forward fill" name makes the code more readable for anyone reviewing it—no need to parse what "pad" refers to in this context. That said, if you encounter pad in legacy code, you can be confident it’s doing the exact same thing as ffill.
For completeness, the same alias relationship applies to backward filling: backfill is the alias for bfill, and bfill is the more commonly used option.
内容的提问来源于stack exchange,提问作者jhourback
相关产品推荐
相关产品推荐

