In order to avoid dividing by zero, the following logic is aimed to calculate a percentage change and skips the values where the prior month has 0 in values. However, the following would yield all percentage change to null even though there are valid non-NaN non-zero numbers in the referred columns.
df_ex['metric_diff'] = (df_ex['metric_lastmonth'] - df_ex['metric_thismonth'])
try:
df_ex['metric_pctdiff'] = (df_ex['metric_lastmonth'] - df_ex['metric_thismonth'])/df_ex['metric_thismonth']
except ZeroDivisionError:
df_ex['metric_pctdiff'] = np.nan
print(len(df_ex[df_ex['metric_diff'].notna()]))
521
print(len(df_ex[df_ex['metric_pctdiff'].notna()]))
0
The outputs indicate that there are nominal difference with non-NaN values, yet the percentage difference comparison yields all NaN values when compared the same two columns. Is there a logic error I made? What went wrong here?
Additional details:
here is a sample of the Dataframe.
and in this example, there are two rows where we have non-null values from last month.