[Python] How to set a cell value based on the time range in DatetimeIndex in Pandas

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

  1. Stack

    Stack Membro Participativo

    I am trying to create a new column in a pandas dataframe, where the values are based on ranges of the time (hours and minute) of the DatetimeIndex.

    Here is my dataframe:

    DatetimeIndex col_1
    2020-07-10 10:00:00+00:00 A
    2020-07-10 10:30:00+00:00 B
    2020-07-10 11:00:00+00:00 C
    2020-07-10 11:30:00+00:00 D
    2020-07-11 10:00:00+00:00 E
    2020-07-11 10:30:00+00:00 F
    2020-07-11 11:00:00+00:00 G
    2020-07-11 11:30:00+00:00 H


    I would like to create a new column where the value assigned to it is 0 if the time is between 10:00 and 11:00 and 1 if the time is between 11:00 and 12:00.

    So my new dataframe would look like this:

    DatetimeIndex col_1 col_2
    2020-07-10 10:00:00+00:00 A 0
    2020-07-10 10:30:00+00:00 B 0
    2020-07-10 11:00:00+00:00 C 1
    2020-07-10 11:30:00+00:00 D 1
    2020-07-11 10:00:00+00:00 E 0
    2020-07-11 10:30:00+00:00 F 0
    2020-07-11 11:00:00+00:00 G 1
    2020-07-11 11:30:00+00:00 H 1


    I tried using pandas.between_time() and pandas.indexer_between_time() but with no success.

    Continue reading...

Compartilhe esta Página