为什么测试“NaN==NaN”不适用于从pandas数据帧中删除?

2024-04-25 00:03:20 发布

您现在位置:Python中文网/ 问答频道 /正文

请解释一下熊猫是如何对待NaN's的,因为下面的逻辑对我来说似乎是“坏的”,我尝试了各种方法(如下所示)来删除空值。

我使用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只给出所有{}s的一系列。没有什么是NaNs。。。令人困惑。
  • 同样地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!!!

Tags: csv方法testread条目逻辑nancomments
2条回答

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

>>> 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).

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

对列使用Series方法^{}不会影响原始数据帧,但可以执行您希望的操作:

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

^{}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'])

相关问题 更多 >