[Python] How to accurately implement typing with pandas?

Discussão em 'Python' iniciado por Stack, Fevereiro 14, 2025.

  1. Stack

    Stack Membro Participativo

    So I've got a class, and I've defined

    class Example():
    self.database: pd.DataFrame = pd.DataFrame(
    columns = ["Example", "Time Example" : "datetime64[ns]"]
    ).astype({"Example": float})


    Now, when I try to do operations such as

    def example_time_method(self, id: str, date: dt.datetime):
    elapsed = date - self.database.loc[id, "Time Example"]

    def example_float_method(self, id: str, num: float):
    diff = num - self.database.loc[id, "Example"]


    I get the errors:

    • Operator "-" not supported for types "datetime" and "Scalar"
    • Operator "-" not supported for type "Scalar" when expected type is "_ScalarLike_co"

    Now, for some reason, if I change it to loc[id]["Example"] instead of loc[id, "Example"], this works for the float example. However, for the datetime example I still get an error:

    • Operator "-" not supported for types "datetime" and "Unknown | Series[Unknown]"

    I'm really confused as to what's going on, any help would be appreciated!

    I've tried adding typing, doing conversions (e.g. float(...)) but the errors always go further in. Obviously I've tried the above of changing the [a, b] to [a] but that just produces a different error. And even when it works for the float case, I want to know why it works!

    Continue reading...

Compartilhe esta Página