How can I stop mypy complaining when comparing a pd.Series to single value?

Question:

I have the following code:

result = pd.Series([pd.Timedelta(minutes=2)]) > pd.Timedelta(hours=1)

However mypy complains with the following:

error: Unsupported operand types for > ("Series[Any]" and "Timedelta")

I also tried:

s: pd.Series[pd.Timedelta] = pd.Series([pd.Timedelta(minutes=2)])
result = s > pd.Timedelta(hours=1)

But that also gives an error:

error: Unsupported operand types for > ("Series[Timedelta]" and "Timedelta")

Note that mypy doesn’t complain if I just have a series with ints such as pd.Series([10]) > 3.

What am I doing wrong?

Asked By: Dan

||

Answers:

I think your pandas or python version is outdated u can install the latest version and then try u can take a reference of my screenshot for version of python and pandas of 3.10.5, 1.4.3
enter image description here
if further, u faced a problem comment to me with a screenshot

Answered By: Noman

pandas-stubs 1.4.3.220724 does not allow Timedelta in pandas.Series.__gt__.

This has been fixed in pandas-stubs 1.4.3.220801.

Workarounds for earlier versions

1. Exclude that line from type checking

s = pd.Series([pd.Timedelta(minutes=2)])
result = s > pd.Timedelta(hours=1)  # type: ignore

2. Use the flexible wrapper of that comparison operator

In this case, pandas.Series.gt.

s = pd.Series([pd.Timedelta(minutes=2)])
result = s.gt(pd.Timedelta(hours=1))

3. Explicitly declare to type checkers that it’s actually supported

from typing import cast

import pandas as pd


class SupportsGtTimedelta:
    def __gt__(self, other: pd.Timedelta): ...


s = cast(SupportsGtTimedelta, pd.Series([pd.Timedelta(minutes=2)]))
result = s > pd.Timedelta(hours=1)
Answered By: aaron
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.