df.fillna() 缺失值填充
pd.DataFrame.fillna()
使用指定的方法填充NA / NaN值
DataFrame.fillna(value = None,method = None,axis = None,inplace = False,limit = None,downcast = None)
参数:
- values: dict, Series, or DataFrame,用于替换空值的值,该值不能是list,如果指定某列,则会是字典的形式
- method:{‘backfill’, ‘bfill’, ‘pad’, ‘ffill’, None}, default None,填充方法(向下填充,还是向上,和replace的用法一致)
- axis:{0 or ‘index’, 1 or ‘columns’},填充的方向
- inplace:bool, default False,if True means 修改原文件
- limit:int, default None,限制填充个数
- downcast:dict, default is None
官网例子
df = pd.DataFrame([[np.nan, 2, np.nan, 0], [3, 4, np.nan, 1], [np.nan, np.nan, np.nan, 5], [np.nan, 3, np.nan, 4]], columns=list('ABCD')) df
A B C D
0 NaN 2.0 NaN 0
1 3.0 4.0 NaN 1
2 NaN NaN NaN 5
3 NaN 3.0 NaN 4
将所有NaN元素替换为0
df.fillna(0)
A B C D
0 0.0 2.0 0.0 0
1 3.0 4.0 0.0 1
2 0.0 0.0 0.0 5
3 0.0 3.0 0.0 4
我们还可以向前或向后传播非null值
df.fillna(method='ffill')
A B C D
0 NaN 2.0 NaN 0
1 3.0 4.0 NaN 1
2 3.0 4.0 NaN 5
3 3.0 3.0 NaN 4
将“ A”,“ B”,“ C”和“ D”列中的所有NaN元素分别替换为0、1、2和3
values = {'A': 0, 'B': 1, 'C': 2, 'D': 3} df.fillna(value=values)
A B C D
0 0.0 2.0 2.0 0
1 3.0 4.0 2.0 1
2 0.0 1.0 2.0 5
3 0.0 3.0 2.0 4
仅替换第一个NaN元素
df.fillna(value=values, limit=1)
A B C D
0 0.0 2.0 2.0 0
1 3.0 4.0 NaN 1
2 NaN 1.0 NaN 5
3 NaN 3.0 NaN 4