pandas-dev / pandas

Flexible and powerful data analysis / manipulation library for Python, providing labeled data structures similar to R data.frame objects, statistical functions, and much more
https://pandas.pydata.org
BSD 3-Clause "New" or "Revised" License
43.51k stars 17.88k forks source link

BUG: resampling error when date_range includes a single DST #35219

Closed Flix6x closed 4 years ago

Flix6x commented 4 years ago

Code Sample, a copy-pastable example


>>> import pandas as pd

>>> # works as expected (note the daylight savings transitions in the head and tail)
>>> pd.Series(1., pd.date_range('2020-03-28','2020-10-27', freq='D', tz="Europe/Amsterdam")).resample('24H').pad()

2020-03-28 00:00:00+01:00    1.0
2020-03-29 00:00:00+01:00    1.0
2020-03-30 01:00:00+02:00    1.0
2020-03-31 01:00:00+02:00    1.0
2020-04-01 01:00:00+02:00    1.0
                            ... 
2020-10-23 01:00:00+02:00    1.0
2020-10-24 01:00:00+02:00    1.0
2020-10-25 01:00:00+02:00    1.0
2020-10-26 00:00:00+01:00    1.0
2020-10-27 00:00:00+01:00    1.0
Freq: 24H, Length: 214, dtype: float64

>>> # fails unexpectedly
>>> pd.Series(1., pd.date_range('2020-03-28','2020-03-31', freq='D', tz="Europe/Amsterdam")).resample('24H').pad()

Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/home/felix/anaconda3/envs/bvp-venv/lib/python3.6/site-packages/pandas/core/resample.py", line 453, in pad
    return self._upsample("pad", limit=limit)
  File "/home/felix/anaconda3/envs/bvp-venv/lib/python3.6/site-packages/pandas/core/resample.py", line 1092, in _upsample
    result.index = res_index
  File "/home/felix/anaconda3/envs/bvp-venv/lib/python3.6/site-packages/pandas/core/generic.py", line 5287, in __setattr__
    return object.__setattr__(self, name, value)
  File "pandas/_libs/properties.pyx", line 67, in pandas._libs.properties.AxisProperty.__set__
  File "/home/felix/anaconda3/envs/bvp-venv/lib/python3.6/site-packages/pandas/core/series.py", line 401, in _set_axis
    self._data.set_axis(axis, labels)
  File "/home/felix/anaconda3/envs/bvp-venv/lib/python3.6/site-packages/pandas/core/internals/managers.py", line 178, in set_axis
    f"Length mismatch: Expected axis has {old_len} elements, new "
ValueError: Length mismatch: Expected axis has 4 elements, new values have 3 elements

Problem description

In my first example, resampling from an offset of 1 day to an offset of 24 hours works as expected, but only when the start and end of the DatetimeIndex share the same timezone. In my second example the date range start and ends in a different timezone due to a daylight savings transition on 29 March 2020, for which resampling to 24 hours fails.

Possibly related issue:

Expected Output


>>> pd.Series(1., pd.date_range('2020-03-28','2020-03-31', freq='D', tz="Europe/Amsterdam")).resample('24H').pad()

2020-03-28 00:00:00+01:00    1.0
2020-03-29 00:00:00+01:00    1.0
2020-03-30 01:00:00+02:00    1.0
Freq: 24H, Length: 3, dtype: float64

Output of pd.show_versions()

INSTALLED VERSIONS ------------------ commit : None python : 3.7.7.final.0 python-bits : 64 OS : Linux OS-release : 4.9.0-11-amd64 machine : x86_64 processor : byteorder : little LC_ALL : None LANG : en_US.UTF-8 LOCALE : en_US.UTF-8 pandas : 1.0.5 numpy : 1.19.0 pytz : 2020.1 dateutil : 2.8.1 pip : 20.1.1 setuptools : 47.3.1.post20200622 Cython : None pytest : None hypothesis : None sphinx : None blosc : None feather : None xlsxwriter : None lxml.etree : None html5lib : None pymysql : None psycopg2 : None jinja2 : None IPython : None pandas_datareader: None bs4 : None bottleneck : None fastparquet : None gcsfs : None lxml.etree : None matplotlib : None numexpr : None odfpy : None openpyxl : None pandas_gbq : None pyarrow : None pytables : None pytest : None pyxlsb : None s3fs : None scipy : None sqlalchemy : None tables : None tabulate : None xarray : None xlrd : None xlwt : None xlsxwriter : None numba : None
TomAugspurger commented 4 years ago

The issue is possibly around here

   1090         # if we have the same frequency as our axis, then we are equal sampling
   1091         if limit is None and to_offset(ax.inferred_freq) == self.freq:
   1092             result = obj.copy()
-> 1093             result.index = res_index
   1094         else:
   1095             result = obj.reindex(
   1096                 res_index, method=method, limit=limit, fill_value=fill_value
   1097             )

Do we also need a length check in that if condition? Can you investigate @Flix6x?

TomAugspurger commented 4 years ago

And given the discussion in https://github.com/pandas-dev/pandas/issues/35248, is this a duplicate or distinct?

Flix6x commented 4 years ago

Adding the length check and len(obj) == len(res_index) to line 1091 indeed resolves the problem.

I would have actually expected the preceding offset comparison to fail:

>>> pd.offsets.Day(1) == pd.offsets.Hour(24)
True

To me, adding the length check remedies a symptom of maintaining this equality. Both date_range() and resample() treat pd.offsets.Day(1) as a calendar day, in which case this equality shouldn't hold.

This issue is distinct from #35248, and both are symptoms of #22864. Your suggested fix would resolve this issue (which deals with offsets only), but not #35248 (which deals with pandas offsets versus datetime timedeltas).

Would you like me to make a pull request (with or without test)?

TomAugspurger commented 4 years ago

That'd be great (including a test).

jreback commented 4 years ago

Adding the length check and len(obj) == len(res_index) to line 1091 indeed resolves the problem.

I would have actually expected the preceding offset comparison to fail:

>>> pd.offsets.Day(1) == pd.offsets.Hour(24)
True

To me, adding the length check remedies a symptom of maintaining this equality. Both date_range() and resample() treat pd.offsets.Day(1) as a calendar day, in which case this equality shouldn't hold.

This issue is distinct from #35248, and both are symptoms of #22864. Your suggested fix would resolve this issue (which deals with offsets only), but not #35248 (which deals with pandas offsets versus datetime timedeltas).

Would you like me to make a pull request (with or without test)?

yeah we had quite some discussion about #22864 and actually @mroeschke pushed a patch, but its too big of a change to do in a minor release; we would have to wait till 2.0 for this.