[Python] Pandas cummax datetime when NaT values exist

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

  1. Stack

    Stack Membro Participativo

    I have a column of "Purchase Dates". The column either contains NaT or an actual date.

    Date Last_Purchase Cummax_Purchase
    2010-05-28 NaT NaT
    2010-06-01 2010-06-01 2010-06-01
    2010-06-02 2010-06-02 2010-06-02
    2010-06-03 NaT NaT
    2010-06-04 NaT NaT


    I want to do a cummax() on the column such that it returns the most recent purchase date.

    data['Purchase_Date'] = numpy.where(data['Buy Signal'] == True, data.index.astype(str), pandas.NaT)
    data['Cummax_Purchase'] = pandas.to_datetime(data['Purchase_Date']).cummax()


    The above cummax returns an NaT whenever their is an NaT in a corresponding row, not the cummax. But whenever I change the pandas.NaT to 0, then it works. But I want to return NaT values when there is an NaT.

    Here's a small sample code:

    data = pandas.DataFrame(
    {"Purchase Dates" : pandas.to_datetime(['01-01-2020', '02-01-2020',None,'04-01-2020'])}, index=pandas.to_datetime(['01-01-2020','02-01-2020','03-01-2020','04-01-2020']))
    data['Cummax_date'] = df['Purchase Dates'].cummax()

    Continue reading...

Compartilhe esta Página