Issue
I am trying to create new a calculated date column by subtracting two date columns, but only if a condition in a 3rd column (column_name) is met (it cannot be NaN). This is the code I have so far but it is not working (see error below). Thank you in advance as I am a beginner.
def function(column_name):
if df[df.column_name.notna()] == True:
return (df['date1']-df['date2']).astype('timedelta64[s]')
else:
return 'Null'
df['New_Calculated_Column'] = df['columnname'].apply(function)
Received this error:
Unexpected exception formatting exception. Falling back to standard exception
Solution
You can use pd.Series.where, e.g. with df on the 1st floor. Here's the code:
df['new']=df['col'].where(df['col'].isna(),df['date1'].sub(df['date2']).astype('timedelta64[s]'))
Answered By - cxywz
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.