pandas用fillna填充NaN值
energy_百分百 人气:11. 参数解析
1.1 inplace参数
取值:True、False
True:直接修改原对象
False:创建一个副本,修改副本,原对象不变(缺省默认)
1.2 method参数
取值 : {‘pad’, ‘ffill’,‘backfill’, ‘bfill’, None}, default None
pad/ffill:用前一个非缺失值去填充该缺失值
backfill/bfill:用下一个非缺失值填充该缺失值
None:指定一个值去替换缺失值(缺省默认这种方式)
1.3 limit参数:
限制填充个数
1.4 axis参数
修改填充方向
补充
isnull 和 notnull 函数用于判断是否有缺失值数据
- isnull:缺失值为True,非缺失值为False
- notnull:缺失值为False,非缺失值为True
2. 代码实例
#导包 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
2.1 常数填充
2.1.1 用常数填充
#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
2.1.2 用字典填充
第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
2.2 使用inplace参数
print (df1.fillna(0,inplace=True)) print ("-------------------------") print (df1)
运行结果:
在这里插入代码片
2.3 使用method参数
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.4 使用limit参数
用下一个非缺失值填充该缺失值且每列只填充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
2.5 使用axis参数
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基础运算以及空值填充
总结
加载全部内容