填补缺失值的两种方法ffill和bfill

2022-09-18 13:48:18

Pandas填充缺失值两种方法:bfill/ffill对比

import pandasas pdimport numpyas np
"""
在dataframe中建立缺失值的两种方法:
np.nan和None
"""
df_=pd.DataFrame({'ID':range(5),'Height':range(5,10),'Gender':['male',np.nan,None,'famle',np.nan],'col3':[1.3,np.nan,3.6,np.nan,5.8]}).set_index('ID')

df_
HeightGendercol3
ID
05male1.3
16NaNNaN
27None3.6
38famleNaN
49NaN5.8
'''
bfill:向前填充
ffill:向后填充
默认 axis=0(列方向)  vs  axis=1(行方向)
'''
df1=df_.fillna(method='bfill',axis=1)
df1
HeightGendercol3
ID
05male1.3
16NaNNaN
273.63.6
38famleNaN
495.85.8
df2=df_.fillna(method='bfill',axis=0)
df2
HeightGendercol3
ID
05male1.3
16famle3.6
27famle3.6
38famle5.8
49NaN5.8
df3=df_.fillna(method='ffill',axis=0)
df3
HeightGendercol3
ID
05male1.3
16male1.3
27male3.6
38famle3.6
49famle5.8
df3['col3'].replace([5.8,1.3],[np.nan,np.nan],inplace=True)
df3
HeightGendercol3
ID
05maleNaN
16maleNaN
27male3.6
38famle3.6
49famleNaN
df4=df3.fillna(method='ffill',axis=1)
df4
HeightGendercol3
ID
05malemale
16malemale
27male3.6
38famle3.6
49famlefamle
  • 作者:zyq_go
  • 原文链接:https://blog.csdn.net/weixin_43041009/article/details/106567123
    更新时间:2022-09-18 13:48:18