Home > Back-end >  Validation of time and updating another column in pandas
Validation of time and updating another column in pandas

Time:10-15

df['r_time'] = pd.DatetimeIndex(df['createTimestamp']).time
df1 = df[df['Region'].str.contains('to be updated')]

for ind in df1.index:
    if df1['r_time'] < '8:00:00':
        df1['Region'] = 'Americas'

ending with below error

TypeError: '<' not supported between instances of 'datetime.time' and 'str'

CodePudding user response:

You can create time column by to_datetime, then instead comapre with string 8:00:00 convert it to times and set new values to column with DataFrame.loc and chained both mask by & for bitwise AND:

times = pd.to_datetime(df['createTimestamp']).dt.time 

m1 = times < pd.to_datetime('8:00:00').time()

m2 = df['Region'].str.contains('to be updated')

df.loc[m1 & m2, 'Region'] = 'Americas'

CodePudding user response:

You can use two masks, not that you cannot compare directly a time to a string, you need to use pd.Timestamp:

# is the region to be updated?
m1 = df['Region'].str.contains('to be updated')
# is the time before 8:00:00?
m2 = (pd.to_datetime(df['createTimestamp']).dt.time
        .lt(pd.Timestamp('8:00:00').time())
     )

# update
df.loc[m1&m2, 'Region'] = 'Americas'
  • Related