我有一個從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'
但是這並沒有按照預期工作。
在你的第一個函數中,如果row ['FFD']
哇 - 多麼簡單。只需添加第一條建議並從中獲得完美結果即可。如果行['FFD']和...做什麼? –
哦,是的,謝謝! –