dimanche 23 août 2020

How to write multiple if statements with one else in lambda functions - pandas

I am trying to create a column which lets me know if a student submitted his/her marks before the first deadline (if submitted then return 1, else 0) deadline is Jan 3, 2017 - 11:59:59 PM.

I have created columns such as 'year','month','day','hour','mins','secs' derived from a single column called 'submit_time' and all the columns are in dtype = 'int':

df['day'] = df.submit_time.dt.day
df['month'] = df.submit_time.dt.month
df['year'] = df.submit_time.dt.year
df['hour'] = df.submit_time.dt.hour
df['mins'] = df.submit_time.dt.minute
df['secs'] = df.submit_time.dt.second

I have tried the following methods:

df['first_deadline'] = df[['year','month','day','hour','mins','secs']].apply(lambda x:1 if x['day'] <= 3  & if x['month'] = 1 & if x['year'] = 2017 & if x['hour'] <= 23 & if x['mins'] <= 59 & if x['secs'] <= 59 else 0, axis=1 )

df['first_deadline'] = df[['year','month','day','hour','mins','secs']].apply(lambda x:1 if (x['day'] <= 3  & if x['month'] = 1 & if x['year'] = 2017 & if x['hour'] <= 23 & if x['mins'] <= 59 & if x['secs'] <= 59) else 0, axis=1 )

df['first_deadline'] = df[['year','month','day','hour','mins','secs']].apply(lambda x:1 if (x['day'] <= 3  & x['month'] = 1 & x['year'] = 2017 & x['hour'] <= 23 & x['mins'] <= 59 & x['secs'] <= 59) else 0, axis=1 )

Is it wrong to write so many if statements in one go, or is my format wrong please let me know if there is a simpler way to this, i am new to this!

Expected output:

first_deadline
1
1
0
1
0

And i get the following error

 File "<ipython-input-67-3bb52937c755>", line 1
    df['first_deadline'] = df[['year','month','day','hour','mins','secs']].apply(lambda x:1 if (x['day'] <= 3  & if x['month'] = 1 & if x['year'] = 2017 & if x['hour'] <= 23 & if x['mins'] <= 59 & if x['secs'] <= 59) else 0, axis=1 )
                                                                                                                 ^
SyntaxError: invalid syntax

Aucun commentaire:

Enregistrer un commentaire