pandas series.ffill() 方法如何工作?

pandasserver side programmingprogramming更新于 2025/5/21 3:22:17

pandas series.ffill() 方法的工作原理与带有"method = ffill"函数的 series.fillna() 相同,或者我们可以说 series.ffill() 是正向填充方法的同义词。

series.ffill() 方法使用正向填充方法替换给定系列对象中的 Nan 或 NA 值。此方法的参数为 inplace、axis、limit 和 downcast。

它没有 value 和 method 之类的参数。因为它将系列元素作为替换值,并使用正向填充方法填充缺失值。

示例 1

在下面的示例中,我们将 ffill() 方法应用于具有一些 Nan 值的对象数据的系列对象,并且默认参数未更改。

# 导入 pandas 包
import pandas as pd
import numpy as np

# 创建系列
s = pd.Series(["a", np.nan, np.nan, "b", "c", np.nan, "d", "e"])
print(s)

# 替换缺失值
result = s.ffill()
print('Result:')
print(result)

输出

输出如下所示 −

0    a
1    NaN
2    NaN
3    b
4    c
5    NaN
6    d
7    e
dtype: object

Result:
0    a
1    a
2    a
3    b
4    c
5    c
6    d
7    e
dtype: object

在上面的输出块中,我们可以注意到,series 对象的缺失值已成功更新为上一行值。

示例 2

以下示例已将 inplace 参数指定为 True,以便将修改应用于原始 series 对象。

# 导入 pandas 包
import pandas as pd
import numpy as np

# 创建 series
s = pd.Series([np.nan, np.nan, 27, 61, np.nan, 93, np.nan, 68, 70, np.nan])
print(s)

# 替换缺失值值
s.ffill(inplace=True)
print('Result:')
print(s)

解释

如果您不更改 inplace 参数的默认值,则它将创建一个具有更新值的新系列,并且此 inplace 参数的默认值为 False。

输出

输出如下所示 −

0    NaN
1    NaN
2    27.0
3    61.0
4    NaN
5    93.0
6    NaN
7    68.0
8    70.0
9    NaN
dtype: float64

Result:
0    NaN
1    NaN
2    27.0
3    61.0
4    61.0
5    93.0
6    93.0
7    68.0
8    70.0
9    70.0
dtype: float64

我们可以注意到索引位置 0 和 1 处的 Nan 值保持不变,这是因为没有先前的值可用于执行前向填充操作。


相关文章