数据分析 三 pandas空值清洗

有两种丢失数据:

  • None
  • np.nan(NaN)
 
import pandas as pd
import numpy as np
from pandas import Series,DataFrame

 

1. None

None是Python自带的,其类型为python object。因此,None不能参与到任何计算中。

print(type(None))

<class 'NoneType'>

2. np.nan(NaN)

np.nan是浮点类型,能参与到计算中。但计算的结果总是NaN

print(type(np.nan))

<class 'float'>

 np.nan +1   ==> nan

3. pandas中的None与NaN

 

1) pandas中None与np.nan都视作np.nan

 创建DataFrame
df = DataFrame(data= np.random.randint(0,100,size=(8,10)))
df

#将某些数组元素赋值为nan

df.iloc[2,5]=None
df.iloc[5,3]=None
df.iloc[7,7]=np.nan
df  # 结果都是nan

 

2) pandas处理空值操作

 

# 删行
# 相邻赋值

 

  • isnull()
  • notnull()
  • dropna(): 过滤丢失数据
  • fillna(): 填充丢失数据

(1)判断函数

  • isnull()
  • notnull()
df.isnull().any(axis=1) 



=======================
0    False
1    False
2     True
3    False
4    False
5     True
6    False
7     True
dtype: bool
df.notnull().all(axis=1)

============
0     True
1     True
2    False
3     True
4     True
5    False
6     True
7    False
dtype: bool

固定搭配 isnull+any
notnull+all

    •   df.notnull/isnull().any()/all()
#过滤df中的空值(只保留没有空值的行)
df.loc[df.notnull().all(axis=1)]

 

df.dropna()就可以替代上面多步的操作,一步到位

     可以选择过滤的是行还是列(默认为行):axis中0表示行,1表示的列

df.dropna(axis=0) 

 

(3) 填充函数 Series/DataFrame

  • fillna():value和method参数
  • method=> bfill 后覆盖, ffill 前覆盖 axis =>0列 1行

可以选择前向填充还是后向填充

 
df.fillna(method='bfill',axis=0)   # 列的后覆盖

 

============================================

练习7:

  1. 简述None与NaN的区别

  2. 假设张三李四参加模拟考试,但张三因为突然想明白人生放弃了英语考试,因此记为None,请据此创建一个DataFrame,命名为ddd3

  3. 老师决定根据用数学的分数填充张三的英语成绩,如何实现? 用李四的英语成绩填充张三的英语成绩?

============================================

posted @ 2021-01-02 12:51  蜗牛般庄  阅读(554)  评论(0编辑  收藏  举报
Title
页脚 HTML 代码