Pandas中pd.isnull与pd.isna的关系

最近在使用Pandas时发现判断缺省值时有两个方法,一直在奇怪这两个的用法区别,今天终于下定决心去查找下。

pd.isnull == pd.isna

(1) 有趣的现象

先看下面几行代码:

pd.isnull
>>> <function pandas.core.dtypes.missing.isna(obj)>
pd.isna
>>> <function pandas.core.dtypes.missing.isna(obj)>
pd.isnull == pd.isna
>>> True

为什么?

(2) 原因

首先看pandas 0.21版本的改变,官方文档原文如下:

In order to promote more consistency among the pandas API, we have
added additional top-level functions isna() and notna() that are
aliases for isnull() and notnull(). The naming scheme is now more
consistent with methods like .dropna() and .fillna(). Furthermore in
all cases where .isnull() and .notnull() methods are defined, these
have additional methods named .isna() and .notna(), these are included
for classes Categorical, Index, Series, and DataFrame. (GH15001).
The configuration option pd.options.mode.use_inf_as_null is deprecated,
and pd.options.mode. use_inf_as_na is added as a replacement.

官方文档已经说的很清楚,isna()和notna()是isnull()和notnull()的别名,它们的用法是一样的。
注意:在pandas 0.21之前的版本中是没有isna和notna的,如果pandas版本是之前的老版本,会报错AttributeError: module ‘pandas‘ has no attribute ‘isna‘
需要pip install --upgrade pandas 一下即可。具体可点击链接查看

 

那么,为什么用两个名称不同的方法做相同的事情?

  1. pandas的DataFrame数据类型基于R的DataFrame数据类型,在R语言中,na和null是两种不同的东西,两个类型是分开的。
    (1) null 表示R中的空对象
    (2) NA 表示R中长度为1的逻辑常数,即NA是一个逻辑值,表示逻辑不确定值的结果。
    R中的NA与NULL: https://www.r-bloggers.com/r-na-vs-null/
  2. 同时pandas也是基于numpy,它是构建在numpy之上的。在numpy中,既没有na也没有null,而只有NaN (意思是“Not a Number”),因此,pandas也沿用NaN值。所以造成了isna和isnull两个名称不同但功能相同的情况。
    pandas的isna 、isnull源码: https://github.com/pandas-dev/pandas/blob/master/pandas/core/dtypes/missing.py

简单的说:

  • numpy用isnan()检查是否存在NaN。
  • pandas用isna()或者isnull()检查是否存在NaN。
  • 存在着两种方法,只是因为pandas对R的模仿。
  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值