pandas-空值处理

pandas-空值处理

pandas中的None和NaN

type(None) --类型是 NoneType 空的对象类型

type(NaN) --类型是 float 浮点型

Pandas中None 和 NaN 都视作np.nan

numpy中的三个常量 np.NAN 、np.nan 、np.NaN 都是 float 浮点型

# pandas和numpy中任意两个缺失值不相等(np.nan \!= np.nan)
import numpy as np
import pandas as pd

print(type(np.NAN))
print(np.NAN==np.nan)
print(np.nan==np.nan)
# <class 'float'>
# False
# False

df = pd.Series(data=[None,None,None])
df.loc[:]=None
print(df)
#0    None
#1    None
#2    None

print(type(df.loc[0]))
#dtype: object
#<class 'NoneType'>

空值检测

isna()
isnull()
notnull()
import numpy as np
import pandas as pd


df = pd.DataFrame(data=np.arange(1,21).reshape(4,5),
                  columns=list('abcde'))
df.loc[1,'a'] = np.nan
df.loc[3,'b'] = np.nan
df.loc[0,'e'] = np.nan
print(df)

      a     b   c   d     e
0   1.0   2.0   3   4   NaN
1   NaN   7.0   8   9  10.0
2  11.0  12.0  13  14  15.0
3  16.0   NaN  18  19  20.0

空值检查单独使用

print(df.loc[1,:].isna())
#a     True
#b    False
#c    False
#d    False
#e    False
#Name: 1, dtype: bool

print(df.loc[2:4,:].isnull())
#a      b      c      d      e
#2  False  False  False  False  False
#3  False   True  False  False  False

print(df.loc[:,["a","c"]].notnull())
#       a     c
#0   True  True
#1  False  True
#2   True  True
#3   True  True

空值检查和any(),all()联合使用

isnull()+any()有空值就返回true
notnull()+all()检测表中是否存在空值

df2=df.loc[df.notnull().all(axis=1)]  # 找出不存在空值的 行
print(df2)
      a     b   c   d     e
#2  11.0  12.0  13  14  15.0
#4  21.0  22.0  23  24  25.0

print(df.loc[:,["a","c"]].notnull().all(axis=0))
#a    False
#c     True
#dtype: bool

print(df.loc[:,["a","c"]].notnull().all(axis=1))
#0     True
#1    False
#2     True
#3     True
#dtype: bool


空值删除(过滤)

使用 dropna() 函数可以删除包含任何缺失值的行或列。例如,删除包含任何缺失值的行:

DataFrame.dropna(self, axis=0, how='any', thresh=None, subset=None, inplace=False)

axis : {0或'index',1或'columns'},默认0 确定是否删除包含缺失值的行或列。
how : {'any','all'},默认为'any' 当我们有至少一个NA或全部NA时,确定是否从DataFrame中删除行或列。
		'any':如果存在任何NA值
		'all':如果所有值均为NA
thresh  : int,可选需要许多非NA值
subset  : 类数组,考虑的其他轴上的标签
inplace : bool,默认为False 如果为True,则执行就地操作
return  :  删除了NA条目的DataFrame。
		
dropna(axis=0)    # 删除行
dropna(axis=1)    # 删除列
import numpy as np
import pandas as pd

df = pd.DataFrame(data=np.arange(1,21).reshape(4,5),
                  columns=list('abcde'))
df.loc[1,'a'] = np.nan
df.loc[0,'e'] = np.nan
print(df)
#      a   b   c   d     e
#0   1.0   2   3   4   NaN
#1   NaN   7   8   9  10.0
#2  11.0  12  13  14  15.0
#3  16.0  17  18  19  20.0

df1=df.dropna(axis=0)    # 删除存在空值的行
print(df1)
#      a   b   c   d     e
#2  11.0  12  13  14  15.0
#3  16.0  17  18  19  20.0


df2=df.dropna(axis=1)    # 删除存在空值的列
print(df2)
#    b   c   d
#0   2   3   4
#1   7   8   9
#2  12  13  14
#3  17  18  19

df.dropna(subset=['e'])   # 删除e中存在空值行
#      a   b   c   d     e
#1   NaN   7   8   9  10.0
#2  11.0  12  13  14  15.0
#3  16.0  17  18  19  20.0

空值填充

使用 fillna() 函数可以填充 DataFrame 中的缺失值。

DataFrame.fillna(self, value=None, method=None, axis=None, inplace=False, limit=None, downcast=None, **kwargs)

value : scalar(标量),dict, Series, 或DataFrame,用于填充孔的值
method  : {'backfill','bfill','pad','ffill',None},默认为None
axis : {0或'index',1或'columns'}
import numpy as np
import pandas as pd

df = pd.DataFrame(data=np.arange(1,21).reshape(4,5),
                  columns=list('abcde'))

df2=df.fillna("$", inplace=False)   # 替换成
print(df2)
#      a     b   c   d     e
#0   1.0   2.0   3   4     $
#1     $   7.0   8   9  10.0
#2  11.0  12.0  13  14  15.0
#3  16.0     $  18  19  20.0

df.fillna("88", inplace=True)
print(df)
#      a     b   c   d     e
#0   1.0   2.0   3   4  88.0
#1  88.0   7.0   8   9  10.0
#2  11.0  12.0  13  14  15.0
#3  16.0  88.0  18  19  20.0
df = pd.DataFrame([[np.nan, 2, np.nan, 0],
                    [3, 4, np.nan, 1],
                    [np.nan, np.nan, np.nan, 5],
                    [np.nan, 3, np.nan, 4]],
                   columns=list('ABCD'))
print(df)
#     A    B   C  D
#0  NaN  2.0 NaN  0
#1  3.0  4.0 NaN  1
#2  NaN  NaN NaN  5
#3  NaN  3.0 NaN  4
df1=df.fillna(method='ffill')  # 向前或向后传播非null值
#    A   B   C   D
#0   NaN 2.0 NaN 0
#1   3.0 4.0 NaN 1
#2   3.0 4.0 NaN 5
#3   3.0 3.0 NaN 4

# 将A,  B, C 和  D 列中的所有NaN元素分别替换为0、1、2和3
values = {'A': 0, 'B': 1, 'C': 2, 'D': 3}
df2=df.fillna(value=values)
print(df2)
#	A   B   C   D
#0   0.0 2.0 2.0 0
#1   3.0 4.0 2.0 1
#2   0.0 1.0 2.0 5
#3   0.0 3.0 2.0 4

使用插值方法填充缺失值:

使用 interpolate() 函数可以使用插值方法填充缺失值。例如,使用线性插值:

DataFrame.interpolate(self, method='linear', axis=0, limit=None, inplace=False, limit_direction='forward', limit_area=None, downcast=None, **kwargs)

method : str,默认为‘linear’,‘time’: 处理每日和更高分辨率的数据,‘index’, ‘values’: 使用索引的实际数值,
					'pad':使用现有值填写NaN。‘nearest’, ‘zero’, ‘slinear’, ‘quadratic’, ‘cubic’ 等等


import numpy as np
import pandas as pd

df = pd.DataFrame(data=np.arange(1,21).reshape(4,5),
                  columns=list('abcde'))
df.loc[1,'a'] = np.nan
df.loc[0,'e'] = np.nan
df.loc[2,'d'] = np.nan
print(df)

df1=df.interpolate()
print(df1)

#      a   b   c     d     e
#0   1.0   2   3   4.0   NaN
#1   NaN   7   8   9.0  10.0
#2  11.0  12  13   NaN  15.0
#3  16.0  17  18  19.0  20.0

#	a   b   c     d     e
#0   1.0   2   3   4.0   NaN
#1   6.0   7   8   9.0  10.0
#2  11.0  12  13  14.0  15.0
#3  16.0  17  18  19.0  20.0

参考资料

https://www.cjavapy.com/article/460/

https://www.cjavapy.com/article/541/

https://blog.csdn.net/weixin_31866177/article/details/129824293

https://www.cnblogs.com/wang_yb/p/17610655.html

posted @ 2023-09-08 19:24  贝壳里的星海  阅读(104)  评论(0编辑  收藏  举报