Reset values of a column based on conditions from another column Pandas

Question:

I have df with columns ‘Time’ and ‘Col1’. I would like to write a simple function that changes the values of ‘Col1’ between the time intervals from ‘Time’ column.

I don’t know why the following code produces the following error:

ValueError: The truth value of a Series is ambiguous. Use a.empty,
a.bool(), a.item(), a.any() or a.all().

val = 5
time1 = 200
time2 = 300
def reset_value(df, val, time1, time2):
   df.loc[df['Time'] >= time1 and df['Time']<time2, 'Col1'] = val
   return df
Asked By: serdar_bay

||

Answers:

Use & for bitwise AND and add parentheses:

df.loc[(df['Time'] >= time1) & (df['Time']<time2), 'Col1'] = val

Or use Series.ge and Series.lt:

df.loc[df['Time'].ge(time1) & df['Time'].lt(time2), 'Col1'] = val
Answered By: jezrael
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.