簡體   English   中英

為什么測試`NaN == NaN`不能從pandas dataFrame中刪除?

[英]Why does testing `NaN == NaN` not work for dropping from a pandas dataFrame?

請解釋一下如何在熊貓中對待NaN,因為以下邏輯似乎對我“破壞”,我嘗試了各種方法(如下所示)來刪除空值。

我使用read.csv從CSV文件加載的數據read.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只給出一系列所有False 沒有什么是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!!!

您應該使用isnullnotnull來測試NaN(使用pandas dtypes比使用numpy更強大),請參閱文檔中的“缺少值”

在列上使用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'])

您需要使用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).

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM