Description
Pandas version checks
-
I have checked that this issue has not already been reported.
-
I have confirmed this issue exists on the latest version of pandas.
-
I have confirmed this issue exists on the main branch of pandas.
Reproducible Example
clustered_times = pd.Series([pd.to_datetime("2023-01-01") + pd.Timedelta(seconds = i) for i in range(1000)])
outlier_times = pd.Series([pd.to_datetime("2023-01-01") + pd.Timedelta(seconds = i) for i in range(1000)] + [pd.to_datetime("1970-01-01")])
%%time
outlier_times.reset_index().set_index(0).resample("1s")
CPU times: user 1.77 s, sys: 5.62 s, total: 7.39 s
Wall time: 11.9 s
%%time
clustered_times.reset_index().set_index(0).resample("1s")
CPU times: user 981 µs, sys: 119 µs, total: 1.1 ms
Wall time: 1.03 ms
The resample method can be inefficient when there are data points that fall far outside the "normal" date range being considered for resampling. This is especially noticeable when the DataFrame contains mostly clustered timestamps, but has a few outliers that extend the time range significantly. This causes resample to unnecessarily compute a huge number of empty bins, leading to performance issues.
Proposed Solution
To mitigate this issue, I propose adding a boolean parameter (e.g., optimize=True) to the resample method. When enabled, this would:
Pseudo-code solution:
gaps = series.diff().dropna()
threshold = pd.Timedelta(freq) * 1000 # This value is arbitrary
subgroup_indices = gaps[gaps > threshold].index
# Resample for each subgroup
# pd.concat
Installed Versions
INSTALLED VERSIONS
commit : ba1cccd
python : 3.11.5.final.0
python-bits : 64
OS : Darwin
OS-release : 22.6.0
Version : Darwin Kernel Version 22.6.0: Fri Sep 15 13:41:28 PDT 2023; root:xnu-8796.141.3.700.8~1/RELEASE_ARM64_T6000
machine : arm64
processor : arm
byteorder : little
LC_ALL : None
LANG : None
LOCALE : None.UTF-8
pandas : 2.1.0
numpy : 1.26.0
pytz : 2023.3.post1
dateutil : 2.8.2
setuptools : 68.1.2
pip : 23.2.1
Cython : None
pytest : None
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : None
lxml.etree : 4.9.3
html5lib : None
pymysql : None
psycopg2 : 2.9.9
jinja2 : None
IPython : 8.15.0
pandas_datareader : None
bs4 : 4.12.2
bottleneck : None
dataframe-api-compat: None
fastparquet : None
fsspec : None
gcsfs : None
matplotlib : 3.8.0
numba : None
numexpr : None
odfpy : None
openpyxl : 3.1.2
pandas_gbq : None
pyarrow : None
pyreadstat : None
pyxlsb : None
s3fs : None
scipy : 1.11.2
sqlalchemy : None
tables : None
tabulate : None
xarray : None
xlrd : None
zstandard : None
tzdata : 2023.3
qtpy : None
pyqt5 : None
Prior Performance
No response