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.42k stars 17.84k forks source link

BUG: cannot filter an empty DataFrame by a non-numeric condition #59922

Open sam-s opened 4 days ago

sam-s commented 4 days ago

Pandas version checks

Reproducible Example

import pandas as pd
f = pd.DataFrame()
# this works as expected, returning an empty frame
f[f.index < 5]
# this fails
f[f.index > pd.Timestamp("2024-10-10")]

Issue Description

filtering an empty DataFrame by a non-numeric filter fails with

TypeError: '>' not supported between instances of 'numpy.ndarray' and 'Timestamp'

Expected Behavior

an empty frame should be returned, just like with a numeric condition

Installed Versions

INSTALLED VERSIONS ------------------ commit : 0691c5cf90477d3503834d983f69350f250a6ff7 python : 3.12.6 python-bits : 64 OS : Windows OS-release : 10 Version : 10.0.19045 machine : AMD64 processor : Intel64 Family 6 Model 85 Stepping 7, GenuineIntel byteorder : little LC_ALL : None LANG : en_US.UTF-8 LOCALE : English_United States.1252 pandas : 2.2.3 numpy : 2.1.1 pytz : 2024.1 dateutil : 2.8.2 pip : 24.2 Cython : None sphinx : None IPython : 8.27.0 adbc-driver-postgresql: None adbc-driver-sqlite : None bs4 : 4.12.3 blosc : None bottleneck : None dataframe-api-compat : None fastparquet : None fsspec : 2024.9.0 html5lib : None hypothesis : None gcsfs : None jinja2 : 3.1.4 lxml.etree : 5.3.0 matplotlib : 3.9.2 numba : None numexpr : None odfpy : None openpyxl : 3.1.2 pandas_gbq : None psycopg2 : None pymysql : None pyarrow : None pyreadstat : None pytest : None python-calamine : None pyxlsb : None s3fs : None scipy : 1.14.1 sqlalchemy : None tables : None tabulate : None xarray : None xlrd : None xlsxwriter : None zstandard : 0.23.0 tzdata : 2024.2 qtpy : 2.4.1 pyqt5 : None
sam-s commented 4 days ago

I understand that the errors is caused by pd.DataFrame().index being RangeIndex(start=0, stop=0, step=1) but it seems reasonable that an empty frame should be filterable by any condition.

Barring that, how do I create an empty frame that can be filtered by Timestamp?

sam-s commented 4 days ago

do I really need to type

pd.DataFrame(index=pd.date_range(start=pd.Timestamp("2024-10-10"),freq="s", periods=0))

instead of

pd.DataFrame()
rhshadrach commented 3 days ago

Thanks for the report. I think pandas should consider dtype compatibility even on empty objects. Otherwise you end up with cases where it appears that code works, but only because the objects are empty, and then will fail in cases where they are not empty.