[Python] Pandas Timedelta in months

Discussão em 'Python' iniciado por Stack, Setembro 4, 2025.

  1. Stack

    Stack Membro Participativo

    How can I calculate the elapsed months using pandas? I have write the following, but this code is not elegant. Could you tell me a better way?

    import pandas as pd

    df = pd.DataFrame([pd.Timestamp('20161011'),
    pd.Timestamp('20161101') ], columns=['date'])
    df['today'] = pd.Timestamp('20161202')

    df = df.assign(
    elapsed_months=(12 *
    (df["today"].map(lambda x: x.year) -
    df["date"].map(lambda x: x.year)) +
    (df["today"].map(lambda x: x.month) -
    df["date"].map(lambda x: x.month))))
    # Out[34]:
    # date today elapsed_months
    # 0 2016-10-11 2016-12-02 2
    # 1 2016-11-01 2016-12-02 1

    Continue reading...

Compartilhe esta Página