2017-09-05 49 views
1

我有一個從pd.read-sql查詢創建的pandas列。列中有空日期,它們返回爲如下所示的NoneTypes。使用NoneType評估datetime.date列

FFD 
2014-10-29 
2015-06-03 
None 
2017-05-05 


print(type(stores['FFD'][0])) 
class datetime.date 
print(type(stores['FFD'][2])) 
class'NoneType' 

然後我嘗試運行以下功能:

sixty = now - timedelta(60) 
def f(row): 
    if row['FFD'] < sixty: 
     val = 'SR' 
    return val 

stores['JRSR'] = stores.apply(f, axis = 1) 

這會返回一個錯誤:

TypeError: ("'<' not supported between instances of 'NoneType' and 'datetime.date'", 'occurred at index 10') 

我能夠列轉換爲字符串,出於比較的目的,然而,我需要這個字段作爲下游使用的日期字段。我的轉換代碼是:

stores['FFD'] = pd.to_datetime(stores['FFD']) 
stores['FFD'] = stores['FFD'].dt.strftime("%Y-%m-%d") 

如何讓我的函數在不轉換列的情況下工作?基本上我想我的函數只計算datetime.date對象。我試過了:

def(f)row: 
    if isinstance(row['FFD'], NoneType): 
     val = "" 
    elif row['FFD'] < sixty: 
     val = 'SR' 

但是這並沒有按照預期工作。

+1

在你的第一個函數中,如果row ['FFD']

+0

哇 - 多麼簡單。只需添加第一條建議並從中獲得完美結果即可。如果行['FFD']和...做什麼? –

+0

哦,是的,謝謝! –

回答

1

在第一f功能,改變

if row['FFD'] < sixty:

if row['FFD'] and row['FFD'] < sixty:

解決了OP的問題。

if row['FFD']將評估爲True如果row['FFD']包含任何東西比NoneType0False。這是Pythonic檢查None是否存在的方法。請注意,由於邏輯運算符的短路行爲,檢查None應始終首先放置在複合條件下。所以if row['FFD'] and row['FFD'] < sixty:將工作,但if row['FFD'] < sixty and if row['FFD']不會。