Pandas Timedelta attributes (_m, _s): odd behaviour

Viewed 74

I have witnessed some strange behaviour accessing attributes such as _m or _s from a pandas timedelta object . Let me explain the problem with a minimal example, that I run from the console in PyCharm (PyCharm 2020.2.3 (Community Edition))

>>> import pandas as pd
>>> #  Creating a dataFrame with 2 pandas timedeltas:
... df_test=pd.DataFrame({"Timedeltas":[pd.Timedelta('1 days 1:01:01'), pd.Timedelta('2 days 2:02:02')]})
Timedelta('0 days 00:02:56.230217907')
>>> mean_timedelta=df_test['Timedeltas'].mean()
... print(mean_timedelta._m)
0
>>> mean_timedelta=df_test['Timedeltas'].mean()
... print(mean_timedelta)
... print(mean_timedelta._m)
1 days 13:31:31.500000
31
  • Why isn't 31 printed the first time I executed print(mean_timedelta._m)? And why do I get 0 instead?

  • Why is 31 printed only if I run print(mean_timedelta) before?

1 Answers

mean_timedelta is an object of type Timedelta. The attributes of the objects are not populated when the object is created by assignment. You can check it by accessing the attribute _is_populated.

When you first print the whole object with print(mean_timedelta), the attributes are internally populated. It is the reason why you can then access the attributes such as _m:

mean_timedelta=df_test['Timedeltas'].mean()
print(mean_timedelta.is_populated)
print(mean_timedelta)
print(mean_timedelta.is_populated)
print(mean_timedelta._m)
print(mean_timedelta.is_populated)

Output:

False
1 days 13:31:31.500000
True
31
True

My answer is based on the source code of the class.

To intentionaly populate it you can call:

mean_timedelta._ensure_components()

In case you need to get the minutes in another way, you can do:

print((mean_timedelta.seconds//60)%60)
Related