简体   繁体   English

为什么可以添加pd.Timedelta和None?

[英]Why is it possible to add pd.Timedelta and None?

The code 代码

None + pd.Timedelta("1 day")

evaluates to a strange result: 评估一个奇怪的结果:

Timedelta('-106751 days +00:12:43:145224')

Why does this happen? 为什么会这样?

As mentioned in the comments, this behavior has been fixed in later versions of Pandas. 正如评论中所提到的,此行为已在更高版本的Pandas中得到修复。 From going over the code, it seems to have been fixed for version 0.23 in this commit . 从遍历代码开始,在此提交中似乎已修复了0.23版本。

In a bit more detail - the code for the function that calculates the delta, _binary_op_method_timedeltalike , contains the condition: 更详细一点 - 计算delta的函数代码_binary_op_method_timedeltalike包含以下条件:

elif other is NaT:  # (N)ot-(A)-(T)ime, the time equivalent of NaN
    return NaT

But None is not NaT , and that's the reason for the bug: 但是None NaT ,这就是bug的原因:

>>> None is NaT
False

In the later version, a second condition has been added, first converting other to a Timedelta object, and then testing the condition again, so effectively testing: 在更高版本中,添加了第二个条件,首先将other条件转换为Timedelta对象,然后再次测试条件,以便有效地测试:

>>> Timedelta(None) is NaT
True

So now NaT is returned in the case of None + Timedelta . 所以现在NaTNone + Timedelta的情况下返回。

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

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