Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading