jeudi 2 avril 2020

How to create a categorical variable out of a datetime (.today()) function usinf if statement or lambda function in Python

I am looking to create a categorical variable out of a datetime function, but need to use the datetime function for automation purposes. Its pretty close but just will not work out.

In my first attempt, after filtering the date variable to only retain today and yesterdays observations, tried an if statement: but this converted both dates to the label 'yesterday'

test = master2.\
   query(f'date >= "{pd.Timestamp.today() - pd.Timedelta(days = 8)}"').\
   assign(date2 = 'yesterday' if 'master2.date == {pd.Timestamp.today() - pd.Timedelta(days = 7)}' else 'today')

My second attempt used a lambda function: but this returned the error: ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()

test = master2.\
   query(f'date >= "{pd.Timestamp.today() - pd.Timedelta(days = 8)}"').\
   assign(date2 = master2['date'].apply(lambda x: 'yesterday' if master2.date == '{pd.Timestamp.today() - pd.Timedelta(days = 7)}' else 'today'))

I would be grateful for any advice

Aucun commentaire:

Enregistrer un commentaire