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

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

import pandas as pd
import numpy as 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
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值