2016-12-22 49 views
4

我正在嘗試遍歷列= [myCol]具有空值的數據框。我能夠遍歷數據框好,但是當我指定我只想看到空值我得到一個錯誤。遍歷數據框並選擇空值

最終目標是我想迫使一個值爲Null的字段,這就是爲什麼我要重複以確定哪些是第一個字段。

for index,row in df.iterrows(): 
    if(row['myCol'].isnull()): 
     print('true') 

AttributeError: 'str' object has no attribute 'isnull' 

我試圖指定列=「無」,因爲這是我看到的值當我打印數據幀的迭代。仍然沒有運氣:

for index,row in df.iterrows(): 
    if(row['myCol']=='None'): 
     print('true') 

No returned rows 

任何幫助非常感謝!

+0

您的意思是'如果(行[ 'myCol']是None):'?否則這將比較字符串「None」而不是(單例)對象None。 ' –

+0

您的最終目標不明確。也許你可以提供輸入表和預期輸出表。不知道你試圖用什麼替換空值,它是矢量數據還是其他df col或同一df中的其他col?在R中,如果你試圖用同一個df的值替換空值。簡單的是'df $ myCol < - ifelse(df $ myCol ==「」,df $ FillInColumn,df $ myCol)' – user5249203

回答

2

您可以使用pd.isnull()來檢查值爲null或不是:

for index, row in df.iterrows(): 
    if(pd.isnull(row['myCol'])): 
     print('true') 

但好像你需要df.fillna(myValue)其中myValue是要強制值成是NULL字段。而且要檢查數據框中的NULL字段,您可以調用df.myCol.isnull()而不是循環遍歷行並單獨檢查。


如果列是字符串類型的,你可能還需要檢查它是否是空字符串:

for index, row in df.iterrows(): 
    if(row['myCol'] == ""): 
     print('true') 
+0

這個工作謝謝! – Ariel