2015-11-04 33 views
3

我想使用布爾索引,檢查特定列所在的數據幀的行數而不是NaN值。所以,我做了以下:在熊貓數據框中使用「對立布爾值」的正確方法布爾索引

import pandas as pd 
my_df.loc[pd.isnull(my_df['col_of_interest']) == False].head() 

看到數據幀的片段,包括只有那些沒有價值NaN(最值NaN)。

它的工作,但似乎不夠優雅。我想輸入:

my_df.loc[!pd.isnull(my_df['col_of_interest'])].head() 

但是,那樣會產生一個錯誤。我也花了很多時間在R上,所以也許我會混淆事物。在Python中,我通常在可能的地方使用「not」語法。例如,if x is not none:,但我不能在這裏真正做到。有沒有更優雅的方式?我不喜歡必須進行無意義的比較。

回答

9

通常與熊貓(和numpy),我們使用按位非~,而不是!not(其行爲不能被類型覆蓋)。

雖然在這種情況下我們有notnull,~可以派上用場的情況下,沒有特別的對立方法。

>>> df = pd.DataFrame({"a": [1, 2, np.nan, 3]}) 
>>> df.a.isnull() 
0 False 
1 False 
2  True 
3 False 
Name: a, dtype: bool 
>>> ~df.a.isnull() 
0  True 
1  True 
2 False 
3  True 
Name: a, dtype: bool 
>>> df.a.notnull() 
0  True 
1  True 
2 False 
3  True 
Name: a, dtype: bool 

(爲了完整,我會注意的是-,一元負運算符,也將在布爾系列工作,但~是規範的選擇,-已經被廢棄了numpy的布爾數組。)

4

而不是使用pandas.isnull(),您應該使用pandas.notnull()來查找列不具有空值的行。實施例 -

import pandas as pd 
my_df.loc[pd.notnull(my_df['col_of_interest'])].head() 

pandas.notnull()pandas.isnull()布爾逆,如文檔中給出 -

參見
pandas.notnull
pandas.isnull的布爾逆

相關問題