Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

pandas

The code

None + pd.Timedelta("1 day")

evaluates to a strange result:

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

Why does this happen?

like image 568
jhourback Avatar asked Sep 12 '18 17:09

jhourback


People also ask

What does PD Timedelta do?

Timedelta. Represents a duration, the difference between two dates or times. Timedelta is the pandas equivalent of python's datetime.

What will the function To_timedelta output if the input is other than the series and scalar type?

to_timedelta() It will construct Series if the input is a Series, a scalar if the input is scalar-like, otherwise will output a TimedeltaIndex.

What are time deltas?

Timedeltas are differences in times, expressed in difference units, e.g. days, hours, minutes, seconds. They can be both positive and negative. Timedelta is a subclass of datetime.


1 Answers

As mentioned in the comments, this behavior has been fixed in later versions of Pandas. From going over the code, it seems to have been fixed for version 0.23 in this commit.

In a bit more detail - the code for the function that calculates the delta, _binary_op_method_timedeltalike, contains the condition:

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 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:

>>> Timedelta(None) is NaT
True

So now NaT is returned in the case of None + Timedelta.

like image 109
Shovalt Avatar answered Sep 23 '22 12:09

Shovalt