7.1 处理缺失数据
缺失数据在pandas中呈现的方式有些不完美,但对于大多数用户可以保证功能正常。对于数值数据,pandas使用浮点值NaN(Not a Number)表示缺失数据。我们称其为哨兵值,可以方便的检测出来。
处理缺失数据有以下几个方法:
- 判断是否为缺失数据,布尔类型
pd.isnull
pd.notnull
举例说明:
import pandas as pd
import numpy as np
data=pd.Series(["liming",'xiaohong',np.nan,"xiaoshu"])
print(data)
data[3]=None
print(data)
data1=data.isnull()
print(data1)
answer:
0 liming
1 xiaohong
2 NaN
3 xiaoshu
dtype: object
0 liming
1 xiaohong
2 NaN
3 None
dtype: object
0 False
1 False
2 True
3 True
dtype: bool
滤除缺失数据
pd.dropna([axis=0/1],[how="all"])#括号里面是选填条件,默认是0
举例说明:
1、Series一维数组的滤除缺失数据
data2=data.dropna()
print(data2)
0 liming
1 xiaohong
3 xiaoshu
dtype: object
2、DataFrame二维数组滤除缺失数据
data3=pd.DataFrame([
[1., 6.5, 3.], [1., np.nan, np.nan],
[np.nan, np.nan,np.nan], [np.nan, 6.5, 3.]
])
print(data3)
#默认axis=0,滤除只要含有缺失值的数据的行
data4&