简体   繁体   English

'NaTType'对象没有属性'days'

[英]'NaTType' object has no attribute 'days'

I have a column in my dataset which represents a date in ms and sometimes its values is nan (actually my columns is of type str and sometimes its valus is 'nan' ). 我的数据集中有一个列,表示以ms为单位的日期,有时其值为nan (实际上我的列是str类型,有时它的值是'nan' )。 I want to compute the epoch in days of this column. 我想在本专栏的几天内计算时代。 The problem is that when doing the difference of two dates: 问题在于,当做两个日期的差异时:

(pd.to_datetime('now') - pd.to_datetime(np.nan)).days

if one is nan it is converted to NaT and the difference is of type NaTType which hasn't the attribute days . 如果一个是nan ,则转换为NaT ,差异是NaTType类型,它没有属性days

In my case I would like to have nan as a result. 在我的情况下,我希望有nan作为结果。

Other approach I have tried: np.datetime64 cannot be used, since it cannot take as argument nan . 我尝试过的其他方法: np.datetime64不能使用,因为它不能作为参数nan My data cannot be converted to int since int doesn't have nan . 我的数据无法转换为int因为int没有nan

It will just work even if you filter first: 即使您先过滤它也会起作用:

In [201]:
df = pd.DataFrame({'date':[dt.datetime.now(), pd.NaT, dt.datetime(2015,1,1)]})
df

Out[201]:
                        date
0 2015-08-28 12:12:12.851729
1                        NaT
2 2015-01-01 00:00:00.000000

In [203]:
df.loc[df['date'].notnull(), 'days'] = (pd.to_datetime('now') - df['date']).dt.days
df

Out[203]:
                        date  days
0 2015-08-28 12:12:12.851729    -1
1                        NaT   NaN
2 2015-01-01 00:00:00.000000   239

对我来说,从pandas 0.19.2升级到pandas 0.20.3有助于解决此错误。

pip install --upgrade pandas

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM