【问题标题】:Why does testing `NaN == NaN` not work for dropping from a pandas dataFrame?为什么测试“NaN == NaN”不能从熊猫数据帧中删除?
【发布时间】:2013-07-31 22:46:26
【问题描述】:

请解释一下在 pandas 中如何处理 NaN,因为以下逻辑对我来说似乎“被破坏”了,我尝试了各种方法(如下所示)来删除空值。

我使用 read.csv 从 CSV 文件加载的数据框有一个 comments 列,大部分时间都是空的。

marked_results.comments 列长这样;该列的所有其余部分都是 NaN,因此 pandas 将空条目加载为 NaN,到目前为止一切顺利:

0       VP
1       VP
2       VP
3     TEST
4      NaN
5      NaN
....

现在我尝试删除这些条目,只有这样才有效:

  • marked_results.comments.isnull()

所有这些都不起作用:

  • marked_results.comments.dropna() 只给出相同的列,没有任何内容被丢弃,令人困惑。
  • marked_results.comments == NaN 只给出了所有Falses 的系列。没有什么是 NaN……令人困惑。
  • 同样marked_results.comments == nan

我也试过了:

comments_values = marked_results.comments.unique()

array(['VP', 'TEST', nan], dtype=object)

# Ah, gotya! so now ive tried:
marked_results.comments == comments_values[2]
# but still all the results are Falses!!!

【问题讨论】:

  • NaN != NaN - 阅读 Stephen Canon 接受的回复。

标签: python pandas dataframe nan


【解决方案1】:

您应该使用 isnullnotnull 来测试 NaN(使用 pandas dtypes 比使用 numpy 更健壮),请参阅 "values considered missing" in the docs

在列上使用 Series 方法 dropna 不会影响原始数据框,而是做你想做的事:

In [11]: df
Out[11]:
  comments
0       VP
1       VP
2       VP
3     TEST
4      NaN
5      NaN

In [12]: df.comments.dropna()
Out[12]:
0      VP
1      VP
2      VP
3    TEST
Name: comments, dtype: object

dropna DataFrame 方法有一个子集参数(用于删除特定列中包含 NaN 的行):

In [13]: df.dropna(subset=['comments'])
Out[13]:
  comments
0       VP
1       VP
2       VP
3     TEST

In [14]: df = df.dropna(subset=['comments'])

【讨论】:

    【解决方案2】:

    您需要使用math.isnan() 函数(或numpy.isnan)测试NaN。不能用相等运算符检查 NaN。

    >>> a = float('NaN')
    >>> a
    nan
    >>> a == 'NaN'
    False
    >>> isnan(a)
    True
    >>> a == float('NaN')
    False
    

    帮助功能->

    isnan(...)
        isnan(x) -> bool
    
        Check if float x is not a number (NaN).
    

    【讨论】:

      猜你喜欢
      • 2013-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-18
      • 1970-01-01
      • 2019-05-10
      • 2020-09-01
      相关资源
      最近更新 更多