pandas.DataFrame.bfill#
- DataFrame.bfill(*,axis=None,inplace=False,limit=None,limit_area=None)[source]#
Fill NA/NaN values by using the next valid observation to fill the gap.
This method fills missing values in a backward direction along thespecified axis, propagating non-null values from later positions toearlier positions containing NaN.
- Parameters:
- axis{0 or ‘index’} for Series, {0 or ‘index’, 1 or ‘columns’} for DataFrame
Axis along which to fill missing values. ForSeriesthis parameter is unused and defaults to 0.
- inplacebool, default False
If True, fill in-place. Note: this will modify anyother views on this object (e.g., a no-copy slice for a column in aDataFrame).
- limitint, default None
If method is specified, this is the maximum number of consecutiveNaN values to forward/backward fill. In other words, if there isa gap with more than this number of consecutive NaNs, it will onlybe partially filled. If method is not specified, this is themaximum number of entries along the entire axis where NaNs will befilled. Must be greater than 0 if not None.
- limit_area{{None, ‘inside’, ‘outside’}}, default None
If limit is specified, consecutive NaNs will be filled with thisrestriction.
None: No fill restriction.‘inside’: Only fill NaNs surrounded by valid values(interpolate).
‘outside’: Only fill NaNs outside valid values (extrapolate).
Added in version 2.2.0.
- Returns:
- Series/DataFrame
Object with missing values filled.
See also
DataFrame.ffillFill NA/NaN values by propagating the last valid observation to next valid.
Examples
For Series:
>>>s=pd.Series([1,None,None,2])>>>s.bfill()0 1.01 2.02 2.03 2.0dtype: float64>>>s.bfill(limit=1)0 1.01 NaN2 2.03 2.0dtype: float64
With DataFrame:
>>>df=pd.DataFrame({"A":[1,None,None,4],"B":[None,5,None,7]})>>>df A B0 1.0 NaN1 NaN 5.02 NaN NaN3 4.0 7.0>>>df.bfill() A B0 1.0 5.01 4.0 5.02 4.0 7.03 4.0 7.0>>>df.bfill(limit=1) A B0 1.0 5.01 NaN 5.02 4.0 7.03 4.0 7.0