Converting dates with condition

I’m trying to convert a column of dates. There are dates in ‘ms’ unit and Timestamp, I want to convert these dates in ‘ms’ unit in Timestamp too. So, I created this function:

def convert(df):
  if df[df['Timestamp'].str.contains(':') == False]:
     df.Timestamp = pd.to_datetime(df.Timestamp, unit='ms')
return df

df = convert(df)

But is getting this error: ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

I also tried to use np.where but didn’t work…

>Solution :

Your == False statement is applying to the whole dataframe/series, not just the row you want. What you could do instead is just apply your function to those rows using .loc, which will return the rows set by a condition, and the column/s you request:

def convert(df):=
  condition = ~df.Timestamp.str.contains(":") #where this field DOESN'T contain ":"
  df.loc[condition, 'Timestamp'] = \
         pd.to_datetime(df.loc[condition, 'Timestamp'], unit='ms')
return df

df = convert(df)

Leave a Reply