Description
Copy-pastable example
import pandas as pd
import datetime as dt
# Create data
df = pd.DataFrame({'start_date': [dt.date(2019, 3, 31), dt.date(2019, 3, 31)],
'end_date': [dt.date(2019, 3, 31), dt.date(3014, 1, 1)] })
# Calculate duration (timedelta objects)
df['duration'] = df['end_date'] - df['start_date']
# EXAMPLE 1: PROBLEM HERE - THIS FAILS !!!
df['duration_days'] = df['duration'].dt.days
# EXAMPLE 2: This works as a workaround
# df['duration_days'] = df['duration'].apply(lambda x: x.days)
Problem description
dt-accessor cannot extract days
value from timedelta-series
and throws exception:
AttributeErrorTraceback (most recent call last)
<ipython-input-5-ef0f32d83e8e> in <module>
----> 1 df['duration_days'] = df['duration'].dt.days
D:\data_science\bin\anaconda3\envs\nbo2\lib\site-packages\pandas\core\generic.py in __getattr__(self, name)
5061 if (name in self._internal_names_set or name in self._metadata or
5062 name in self._accessors):
-> 5063 return object.__getattribute__(self, name)
5064 else:
5065 if self._info_axis._can_hold_identifiers_and_holds_name(name):
D:\data_science\bin\anaconda3\envs\nbo2\lib\site-packages\pandas\core\accessor.py in __get__(self, obj, cls)
169 # we're accessing the attribute of the class, i.e., Dataset.geo
170 return self._accessor
--> 171 accessor_obj = self._accessor(obj)
172 # Replace the property with the accessor object. Inspired by:
173 # http://www.pydanny.com/cached-property.html
D:\data_science\bin\anaconda3\envs\nbo2\lib\site-packages\pandas\core\indexes\accessors.py in __new__(cls, data)
322 pass # we raise an attribute error anyway
323
--> 324 raise AttributeError("Can only use .dt accessor with datetimelike "
325 "values")
AttributeError: Can only use .dt accessor with datetimelike values
Expected Output
dt-accessor should extract days
value from timedelta-series
without any exceptions.
Output of pd.show_versions()
INSTALLED VERSIONS
commit: None
python: 3.6.8.final.0
python-bits: 64
OS: Windows
OS-release: 7
machine: AMD64
processor: Intel64 Family 6 Model 79 Stepping 1, GenuineIntel
byteorder: little
LC_ALL: None
LANG: None
LOCALE: None.None
pandas: 0.24.1
pytest: None
pip: 19.0.1
setuptools: 40.8.0
Cython: None
numpy: 1.15.4
scipy: 1.2.0
pyarrow: None
xarray: None
IPython: 7.2.0
sphinx: None
patsy: 0.5.1
dateutil: 2.7.5
pytz: 2018.9
blosc: None
bottleneck: None
tables: None
numexpr: None
feather: None
matplotlib: 3.0.2
openpyxl: None
xlrd: None
xlwt: None
xlsxwriter: None
lxml.etree: None
bs4: None
html5lib: None
sqlalchemy: None
pymysql: None
psycopg2: None
jinja2: 2.10
s3fs: None
fastparquet: None
pandas_gbq: None
pandas_datareader: None
gcsfs: None