约定:
1
2
3
|
import pandas as pd
import numpy as np
from numpy import nan as NaN
|
填充缺失数据
fillna()是最主要的处理方式了。
1
2
|
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
|
df1.fillna( 100 )
|
代码结果:
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 |
通过字典填充不同的常数:
1
|
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 |
传入inplace=True直接修改原对象:
1
2
|
df1.fillna( 0 ,inplace = True )
df1
|
代码结果:
0 | 1 | 2 | |
---|---|---|---|
0 | 1.0 | 2.0 | 3.0 |
1 | 0.0 | 0.0 | 2.0 |
2 | 0.0 | 0.0 | 0.0 |
3 | 8.0 | 8.0 | 0.0 |
传入method=” “改变插值方式:
1
2
3
|
df2 = pd.DataFrame(np.random.randint( 0 , 10 ,( 5 , 5 )))
df2.iloc[ 1 : 4 , 3 ] = NaN;df2.iloc[ 2 : 4 , 4 ] = NaN
df2
|
代码结果:
0 | 1 | 2 | 3 | 4 | |
---|---|---|---|---|---|
0 | 6 | 6 | 2 | 4.0 | 1.0 |
1 | 4 | 7 | 0 | NaN | 5.0 |
2 | 6 | 5 | 5 | NaN | NaN |
3 | 1 | 9 | 9 | NaN | NaN |
4 | 4 | 8 | 1 | 5.0 | 9.0 |
1
|
df2.fillna(method = 'ffill' ) #用前面的值来填充
|
代码结果:
0 | 1 | 2 | 3 | 4 | |
---|---|---|---|---|---|
0 | 6 | 6 | 2 | 4.0 | 1.0 |
1 | 4 | 7 | 0 | 4.0 | 5.0 |
2 | 6 | 5 | 5 | 4.0 | 5.0 |
3 | 1 | 9 | 9 | 4.0 | 5.0 |
4 | 4 | 8 | 1 | 5.0 | 9.0 |
传入limit=” “限制填充个数:
1
|
df2.fillna(method = 'bfill' ,limit = 2 )
|
代码结果:
0 | 1 | 2 | 3 | 4 | |
---|---|---|---|---|---|
0 | 6 | 6 | 2 | 4.0 | 1.0 |
1 | 4 | 7 | 0 | NaN | 5.0 |
2 | 6 | 5 | 5 | 5.0 | 9.0 |
3 | 1 | 9 | 9 | 5.0 | 9.0 |
4 | 4 | 8 | 1 | 5.0 | 9.0 |
传入axis=” “修改填充方向:
1
|
df2.fillna(method = "ffill" ,limit = 1 ,axis = 1 )
|
代码结果:
0 | 1 | 2 | 3 | 4 | |
---|---|---|---|---|---|
0 | 6.0 | 6.0 | 2.0 | 4.0 | 1.0 |
1 | 4.0 | 7.0 | 0.0 | 0.0 | 5.0 |
2 | 6.0 | 5.0 | 5.0 | 5.0 | NaN |
3 | 1.0 | 9.0 | 9.0 | 9.0 | NaN |
4 | 4.0 | 8.0 | 1.0 | 5.0 | 9.0 |
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/weixin_38168620/article/details/79596819