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.87k stars 18.02k forks source link

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

Open sam-s opened 1 month ago

sam-s commented 1 month 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 1 month 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 1 month 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 1 month 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.

saldanhad commented 1 month ago

I would like to propose potentially two solutions, to handle this: (1) Update the error message to be more descriptive, suggesting that users ensure compatible types, such as using a DatetimeIndex for Timestamp comparisons, something as below:

TypeError: '>' not supported between instances of 'numpy.ndarray' and 'Timestamp'. Please ensure that the index and comparison object are of compatible types.

(2) Add internal checks to automatically convert the index to a compatible type (e.g., DatetimeIndex when comparing with pd.Timestamp). For example, if a pd.Timestamp is used in a comparison, the logic could convert the index to a DatetimeIndex if it is not already.

Personally, I prefer the first option for its clarity. This would be especially helpful for beginner users.

rhshadrach commented 1 month ago

Please ensure that the index and comparison object are of compatible types.

Isn't this immediately implied by saying '>' is not supported? I do not see what this adds.

(2) Add internal checks to automatically convert the index to a compatible type

I'm opposed here. I do not think pandas should be silently changing dtypes on the user for the comparison. That could be surprising.

saldanhad commented 1 month ago

So are you saying the implementation should be to return an empty dataframe as suggested by OP and not the Error?

rhshadrach commented 1 month ago

No - I think the current behavior of raising is the desired one.