取值:True、False
True:直接修改原对象
False:创建一个副本,修改副本,原对象不变(缺省默认)
取值 : {‘pad’, ‘ffill’,‘backfill’, ‘bfill’, None}, default None
pad/ffill:用前一个非缺失值去填充该缺失值
backfill/bfill:用下一个非缺失值填充该缺失值
None:指定一个值去替换缺失值(缺省默认这种方式)
限制填充个数
修改填充方向
isnull 和 notnull 函数用于判断是否有缺失值数据
#导包 import pandas as pd import numpy as np from numpy import nan as NaN df1=pd.DataFrame([[1,2,3],[NaN,NaN,2],[NaN,NaN,NaN],[8,8,NaN]]) df1
代码结果:
0 1 2
0 1.0 2.0 3.0
1 NaN NaN 2.0
2 NaN NaN NaN
3 8.0 8.0 NaN
#1.用常数填充 print (df1.fillna(100)) print ("-----------------------") print (df1)
运行结果:
0 1 2
0 1.0 2.0 3.0
1 100.0 100.0 2.0
2 100.0 100.0 100.0
3 8.0 8.0 100.0
-----------------------
0 1 2
0 1.0 2.0 3.0
1 NaN NaN 2.0
2 NaN NaN NaN
3 8.0 8.0 NaN
第key列的NaN用key对应的value值填充
df1.fillna({0:10,1:20,2:30})
运行结果:
0 1 2
0 1.0 2.0 3.0
1 10.0 20.0 2.0
2 10.0 20.0 30.0
3 8.0 8.0 30.0
print (df1.fillna(0,inplace=True)) print ("-------------------------") print (df1)
运行结果:
在这里插入代码片
1.method = 'ffill'/'pad':用前一个非缺失值去填充该缺失值
df2 = pd.DataFrame(np.random.randint(0,10,(5,5))) df2.iloc[1:4,3] = None df2.iloc[2:4,4] = None print(df2) print ("-------------------------") print(df2.fillna(method='ffill'))
运行结果:
0 1 2 3 4
0 8 4 4 5.0 6.0
1 5 2 8 NaN 7.0
2 6 3 1 NaN NaN
3 5 4 9 NaN NaN
4 6 5 4 6.0 9.0
-------------------------
0 1 2 3 4
0 8 4 4 5.0 6.0
1 5 2 8 5.0 7.0
2 6 3 1 5.0 7.0
3 5 4 9 5.0 7.0
4 6 5 4 6.0 9.0
2.method = ‘bflii’/‘backfill’:用下一个非缺失值填充该缺失值
df2 = pd.DataFrame(np.random.randint(0,10,(5,5))) df2.iloc[1:4,3] = None df2.iloc[2:4,4] = None print(df2) print ("-------------------------") print(df2.fillna(method='bfill'))
运行结果:
0 1 2 3 4
0 1 0 4 1.0 3.0
1 4 6 4 NaN 2.0
2 4 9 2 NaN NaN
3 9 7 3 NaN NaN
4 6 1 3 5.0 5.0
-------------------------
0 1 2 3 4
0 1 0 4 1.0 3.0
1 4 6 4 5.0 2.0
2 4 9 2 5.0 5.0
3 9 7 3 5.0 5.0
4 6 1 3 5.0 5.0
用下一个非缺失值填充该缺失值且每列只填充2个
df2 = pd.DataFrame(np.random.randint(0,10,(5,5))) df2.iloc[1:4,3] = None df2.iloc[2:4,4] = None print(df2) print ("-------------------------") print(df2.fillna(method='bfill', limit=2))
运行结果:
0 1 2 3 4
0 2 0 4 4.0 0.0
1 7 9 9 NaN 1.0
2 1 7 3 NaN NaN
3 8 5 8 NaN NaN
4 8 6 2 4.0 4.0
-------------------------
0 1 2 3 4
0 2 0 4 4.0 0.0
1 7 9 9 NaN 1.0
2 1 7 3 4.0 4.0
3 8 5 8 4.0 4.0
4 8 6 2 4.0 4.0
axis=0 对每列数据进行操作
axis=1 对每行数据进行操作
df2 = pd.DataFrame(np.random.randint(0,10,(5,5))) df2.iloc[1:4,3] = None df2.iloc[2:4,4] = None print(df2.fillna(method="ffill", limit=1, axis=1))
运行结果:
0 1 2 3 4
0 0.0 4.0 9.0 7.0 2.0
1 6.0 5.0 0.0 0.0 3.0
2 8.0 8.0 8.0 8.0 NaN
3 5.0 5.0 6.0 6.0 NaN
4 7.0 5.0 7.0 4.0 1.0
还有一些pandas的基础运算请参考这篇文章->pandas | DataFrame基础运算以及空值填充
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
长按识别二维码并关注微信
更方便到期提醒、手机管理