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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32269676/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 23:49:44  来源:igfitidea点击:

'NaTType' object has no attribute 'days'

pandasmissing-data

提问by Ruggero Turra

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 strand sometimes its valus is 'nan'). I want to compute the epoch in days of this column. The problem is that when doing the difference of two dates:

我的数据集中有一列表示以毫秒为单位的日期,有时它的值是nan(实际上我的列是类型str,有时它的值是'nan')。我想计算本专栏的天数。问题是在做两个日期的差异时:

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

if one is nanit is converted to NaTand the difference is of type NaTTypewhich hasn't the attribute days.

如果是,nan则将其转换为NaT,并且差异是NaTType没有属性的类型days

In my case I would like to have nanas a result.

就我而言,我希望nan结果如此。

Other approach I have tried: np.datetime64cannot be used, since it cannot take as argument nan. My data cannot be converted to intsince intdoesn't have nan.

我尝试过的其他方法:np.datetime64不能使用,因为它不能作为参数nan。我的数据无法转换为,int因为int没有nan.

回答by EdChum

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

回答by alif

For me upgrading to pandas 0.20.3 from pandas 0.19.2 helped resolve this error.

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

pip install --upgrade pandas