处理丢失数据:
有两种丢失数据
None
np.nan(NaN的形式)
1 None
None是Python自带的,其类型为python object。因此,None不能参与到任何计算中。
import numpy as np import pandas as pd from pandas import Series,DataFrame type(None) #NoneType type(np.nan) #float
np.nan 的数据类型可以进行数据运算
np.nan + 1 得到的数据类型还是np.nan np.nan是浮点类型,能参与到计算中。但计算的结果总是NaN。
2 pandas中的None与NaN
pandas中的None与NaN
1 pandas中的None与np.nan是视作np.nan
创建DataFrame
df = DataFrame(data=np.random.randint(0,100,size=(13,9))) df.iloc[2,4] = None df.iloc[5,5] = np.nan df.iloc[2,2] = None df.iloc[7,3] = None df.iloc[6,8] = None
2 pandas处理空值操作
isnull() 判断数据是否为空,空是True
notnull() 判断数据是否为空,空是False
dropna(): 过滤丢失数据,一般不用,有可能误删数据,
fillna(): 填充丢失数据
df.isnull().any(axis=1) 判断行有空值吗 有空值是True df.notnull().all(axis=1) 判断行有空值吗 有空值是False 一般是这样组合使用的
df.loc[df.notnull().all(axis=1)]取出空值的行
df.dropna(axis=0) 删除行中有空值的行,0是行
3 填充函数 Series/DataFrame的数据
df.fillna(method='ffill',axis=0) ffill 将空值添上上一行元素的数据 df.fillna(method='bfill',axis=0) ffill 将空值添上下一行元素的数据
数据清洗的案例:
文件下载:
https://pan.baidu.com/s/1FFJsgnB1wTW83uJQTJgZew、
#方式一 删除空值的行
temp_df = pd.read_excel('测试数据.xlsx') temp_df = temp_df[[1,2,3,4]] #取出数据的前四列 temp_df.dropna(axis=0) 将空值的行删除
# 方式二 填充空值的行 #首次填充之后对应的结果 test_df = temp_df.fillna(method='bfill',axis=0) #校验test_df中还是否存在空值:查看列中是否还有空值 test_df.isnull().any(axis=0)