pythonpandasdataframedatetime

Fill pandas columns based on datetime condition


Here is the sample code to generate a dataframe.

import pandas as pd
import numpy as np  

dates = pd.date_range("20241218", periods=9600,freq='1MIN')   
df = pd.DataFrame(np.random.randn(9600, 4), index=dates, columns=list("ABCD")) 

I want to fill all the columns with -1 for time between 1:35 to 1:45 for all the dates. Similarly I want to fill all the columns with -2 for the exact time of 1:00 for all the dates. For all other time values, the columns need to be filled with zeros. Please suggest the way forward.


Solution

  • Try:

    df.loc[df.between_time('01:35', '01:45').index] = -1
    df.loc[df.index.time == pd.Timestamp('01:00').time()] = -2
    

    Output can be verified with the similar:

    print(df.between_time('1:35', '1:45').head(15) )
    print(df.loc[df.index.time == pd.Timestamp('01:00').time()])