Pandas中NaN缺失值处理

本文介绍了在Pandas中处理NaN缺失值的方法,包括如何判断缺失值存在、删除缺失值、用均值替换以及处理非np.nan的默认标记。通过pd.notnull()和isnull()函数检查缺失值,使用dropna()删除,fillna()填充,replace()替换特定值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


在这里插入图片描述

一、如何处理nan

在这里插入图片描述

二、电影数据的缺失值处理

  • 电影数据的缺失值处理
# 读取电影数据
movie = pd.read_csv("./data/IMDB-Movie-Data.csv")

在这里插入图片描述

2.1 判断缺失值是否存在

  • pd.notnull()
pd.notnull(movie)
Rank    Title    Genre    Description    Director    Actors    Year    Runtime (Minutes)    Rating    Votes    Revenue (Millions)    Metascore
0    True    True    True    True    True    True    True    True    True    True    True    True
1    True    True    True    True    True    True    True    True    True    True    True    True
2    True    True    True    True    True    True    True    True    True    True    True    True
3    True    True    True    True    True    True    True    True    True    True    True    True
4    True    True    True    True    True    True    True    True    True    True    True    True
5    True    True    True    True    True    True    True    True    True    True    True    True
6    True    True    True    True    True    True    True    True    True    True    True    True
7    True    True    True    True    True    True    True    True    True    True    False    True
np.all(pd.notnull(movie))

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

  • 1、删除

pandas删除缺失值,使用dropna的前提是,缺失值的类型必须是np.nan

# 不修改原数据
movie.dropna()

# 可以定义新的变量接受或者用原来的变量名
data = movie.dropna()
  • 2、均值替换缺失值
# 替换存在缺失值的样本的两列
# 替换填充平均值,中位数
movie['Revenue (Millions)'].fillna(movie['Revenue (Millions)'].mean(), inplace=True)
  • 3、指定值替换
fill_dict={
    'Revenue (Millions)':-100,#Revenue (Millions)列用-100填充
    'Metascore':-10#Metascore列用-10填充
}
movie=movie.fillna(fill_dict)

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

数据是这样的:
在这里插入图片描述
处理思路分析:

  • 1、先替换‘?’为np.nan
    • df.replace(to_replace=, value=)
      • to_replace:替换前的值
      • value:替换后的值
# 把一些其它值标记的缺失值,替换成np.nan
wis = wis.replace(to_replace='?', value=np.nan)
  • 2、在进行缺失值的处理
# 删除
wis = wis.dropna()

三、小结

  • isnull、notnull判断是否存在缺失值【知道】
    • np.any(pd.isnull(movie)) # 里面如果有一个缺失值,就返回True
    • np.all(pd.notnull(movie)) # 里面如果有一个缺失值,就返回False
  • dropna删除np.nan标记的缺失值【知道】
    • movie.dropna()
  • fillna填充缺失值【知道】
    • movie[i].fillna(value=movie[i].mean(), inplace=True)
  • replace替换具体某些值【知道】
    • wis.replace(to_replace="?", value=np.NaN)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值