Open sam-s opened 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
?
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()
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.
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.
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.
So are you saying the implementation should be to return an empty dataframe as suggested by OP and not the Error?
No - I think the current behavior of raising is the desired one.
Pandas version checks
[X] I have checked that this issue has not already been reported.
[X] I have confirmed this bug exists on the latest version of pandas.
[ ] I have confirmed this bug exists on the main branch of pandas.
Reproducible Example
Issue Description
filtering an empty
DataFrame
by a non-numeric filter fails withExpected Behavior
an empty frame should be returned, just like with a numeric condition
Installed Versions