且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

处理np.nan类型的缺失值| 学习笔记

更新时间:2022-09-07 23:23:08

开发者学堂课程【Python 数据分析库 Pandas 快速入门处理np.nan类型的缺失值学习笔记,与课程紧密联系,让用户快速学习知识。

课程地址https://developer.aliyun.com/learning/course/607/detail/8860


处理np.nan类型的缺失值


如何处理 nan

1.判断数据是否为 NaN : pd.isnull(df),pd.notnull(df)

2.存在缺失值 nan,并且是 np.nan:

删除存在缺失值的:dropna(inplace = False)

-注:不会修改原数据,需要接受返回值。

替换缺失值:fillna(value,inplace=True)

value:替换成的值

inplace:

-True:会修改原数据

-False:不替换修改原数据,生成新的对象

3.不是缺失值 nan,有默认标记的


处理缺失值实例  

第一步:判断是否存在 nan 类型的缺失值

In:

import pandas as pd

movie = pd.read_csv ( " ./IMDB/IMDB-Movie-Data.csv " )

movie.head( )    

Out:

In:

pd .isnul1(movie)

Out:

  //这两种方法中间有省略部分,很难看到缺失值

In:

import numpy as np

np.any ( pd.isnull (movie) )  

Out:

True   //返回 True,说明数据中存在缺失值

In:

np.all ( pd.notnul1 (movie) )  

Out:

False   //返回 False,说明数据中存在缺失值

In:

pd.isnull ( movie ).any ( )Rank

Out:

Title

False

Genre

False

Description

False

Director

False

Actors

False

Year

False

Runtime ( Minutes )

False

Rating

False

Votes

False

Revenue (Millions )

True

Metascore

True

dtype: bool   //显示每一个字段是否存在缺失值

In:

pd.notnull ( movie).all()

Out:

Title

True

Genre

True

Description

True

Director

True

Actors

True

Year

True

Runtime ( Minutes )

True

Rating

True

Votes

True

Revenue (Millions )

False

Metascore

False

dtype: bool   //同上

第二步:缺失值处理

方法1∶删除含有缺失值的样本

In:

datal =movie.dropna ()

pd.notnull ( movie ).all()

Out:

Title

True

Genre

True

Description

True

Director

True

Actors

True

Year

True

Runtime ( Minutes )

True

Rating

True

Votes

True

Revenue (Millions )

False

Metascore

False

In:

pd.notnull ( movie ).all()

Out:

Title

True

Genre

True

Description

True

Director

True

Actors

True

Year

True

Runtime ( Minutes )

True

Rating

True

Votes

True

Revenue (Millions )

True

Metascore

True

方法2:替换

In:

//含有缺失值的字段

//Revenue (Millions )

//Metascore

movie["Revenue (Millions)"].fillna(movie["Revenue(Millions) " ].mean(), inplace=True)

movie["Metascore"].fillna(movie["Metascore"].mean( ), inplace=True)

In:

pd.notnull ( movie ).all( )   //缺失值已经处理完毕,不存在缺失值

Out:

Title

True

Genre

True

Description

True

Director

True

Actors

True

Year

True

Runtime ( Minutes )

True

Rating

True

Votes

True

Revenue (Millions )

True

Metascore

True