lundi 18 mars 2019

multiple if conditions in lambda does not work as expected

I have a problem trying to piece together a multiple conditional if.

  • UDF.daysinmonth(x) returns number of days in a month
  • latest_date.month returns the month of datetime object (eg 3 for 2019-3-10) - latest_date=df['offtake_date'].max()

    df.insert(loc=20, column='bbls_mbd_mth',value=df['bbls'] / df['offtake_date'].apply(lambda x: UDF.daysinmonth(x) if x.month!=latest_date.month and x.year!=latest_date.year else latest_date.day))

This doesn't work, if x.month!=latest_date.month and x.year!=latest_date.year. For all of 2019, it returns the latest day in the data rather than the number of days in past months. For 2018, it works fine.

This doesn't work too.

df.insert(loc=20, column='bbls_mbd_mth',value=np.nan)
for i, row in df.iterrows():
    ifor_val = df.at[i,'bbls']/latest_date.day
if ((df.at[i,'offtake_date'].month!=latest_date.month) and (df.at[i,'offtake_date'].year!=latest_date.year)):
    ifor_val = df.at[i,'bbls']/(UDF.daysinmonth(df.at[i,'offtake_date']))
df.at[i,'bbls_mbd_mth'] = ifor_val

it works when i flip the logic

for i, row in df.iterrows():
    ifor_val = df.at[i,'bbls']/(UDF.daysinmonth(df.at[i,'offtake_date'])
    if ((df.at[i,'offtake_date'].month==latest_date.month) and (df.at[i,'offtake_date'].year==latest_date.year)):
        ifor_val = df.at[i,'bbls']/latest_date.day)
    df.at[i,'bbls_mbd_mth'] = ifor_val

I think I am missing something real basic.... any help appreciated

Aucun commentaire:

Enregistrer un commentaire