[英]How to handle NaT values for datetime when doing iterations in python?
I am using below code to convert datetime values to integers. 我使用下面的代码将datetime值转换为整数。 It works great except for NaT values. 除NaT值外,它的效果很好。 If I am doing this in an iteration, how can I handle NaT values so that I don't get errors such as 'NaTType does not support timetuple'? 如果我在迭代中执行此操作,我如何处理NaT值以便不会出现“NaTType不支持timetuple”等错误?
import time
from datetime import datetime
t=datetime.now()
t1=t.timetuple()
int(time.mktime(t1)/60/60/24)
Here is the code to create sample data and what I have tried to iterate so far: 以下是创建示例数据的代码以及到目前为止我尝试迭代的内容:
create data: 创建数据:
df = pd.DataFrame(data={'date':['05/16/16',''], 'Indicator':[1,0]})
df['date']=pd.to_datetime(df['date'])
Data: 数据:
Indicator date
0 1 2016-05-16
1 0 NaT
Iteration code: 迭代码:
def date2int(df):
if df.date:
t=df['date']
t1=t.timetuple()
return int(time.mktime(t1))
df['date2int']=df.apply(date2int,axis=1)
Error message: 错误信息:
Traceback (most recent call last): Traceback(最近一次调用最后一次):
File "", line 1, in df['date2int']=df.apply(date2int,axis=1) 文件“”,第1行,在df ['date2int']中= df.apply(date2int,axis = 1)
File "/Users/Chen/anaconda/lib/python2.7/site-packages/pandas/core/frame.py", line 4042, in apply return self._apply_standard(f, axis, reduce=reduce) 文件“/Users/Chen/anaconda/lib/python2.7/site-packages/pandas/core/frame.py”,第4042行,在申请中返回self._apply_standard(f,axis,reduce = reduce)
File "/Users/Chen/anaconda/lib/python2.7/site-packages/pandas/core/frame.py", line 4138, in _apply_standard results[i] = func(v) 文件“/Users/Chen/anaconda/lib/python2.7/site-packages/pandas/core/frame.py”,第4138行,在_apply_standard结果[i] = func(v)
File "", line 4, in date2int t1=t.timetuple() 文件“”,第4行,在date2int t1 = t.timetuple()
File "pandas/tslib.pyx", line 723, in pandas.tslib._make_error_func.f (pandas/tslib.c:16109) 在pandas.tslib._make_error_func.f文件“pandas / tslib.pyx”,第723行(pandas / tslib.c:16109)
ValueError: ('NaTType does not support timetuple', u'occurred at index 1') ValueError :('NaTType不支持timetuple',你在索引1'发生')
Solution #1: 解决方案#1:
def date2int(df):
if df.date:
t=df['date']
try:
t1=t.timetuple()
return int(time.mktime(t1))
except ValueError:
return None
df['date2int']=df.apply(date2int,axis=1)
Solution #2: 解决方案#2:
df=df.dropna()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.