[Python] How do I use Pandas' infer_objects correctly (v. 2.2.3)

Discussão em 'Python' iniciado por Stack, Janeiro 24, 2025.

  1. Stack

    Stack Membro Participativo

    I try the following example in Pandas 2.2.3:

    outage_mask = pd.Series(([True]*5 + [False]*5)*5, index=pd.date_range("2025-01-01", freq="1h", periods=50))
    [ts for ts in outage_mask.loc[outage_mask.diff().fillna(False)].index]


    This gives me the error message:


    FutureWarning: Downcasting object dtype arrays on .fillna, .ffill, .bfill is deprecated and will change in a future version. Call result.infer_objects(copy=False) instead. To opt-in to the future behavior, set pd.set_option('future.no_silent_downcasting', True)
    ​

    I cannot figure out how to correctly apply this infer_objects. I assume the problem is that the output of diff becomes an 'object' dtype due do containing both NaNs and bools, but for example this does not help:

    [ts for ts in outage_mask.loc[outage_mask.diff().infer_objects(copy=False).fillna(False)].index]


    I can avoid the warning by this clumsy work-around:

    [ts for ts in outage_mask.loc[outage_mask.diff().astype(float).fillna(0.).astype(bool)].index]


    but I would like to understand how to apply the solution from the warning correctly. How do I do that?

    Continue reading...

Compartilhe esta Página