-1

I am trying to calculate % value, in some case the denominator could be blank or zero and if I divide by blank or zero, it gives me infinity but I want the value as zero, not sure how to add in the formula.

Example: my formula is (month3 minus month2)/month2 - I am trying to calculate percentage change between month3 and month2. In the data set I am getting some values for month 2 as zero or blank, how to take care in the code.

dataset["USAGE_MONTH2_INCREASED"]=(
    (dataset.MNTH2_ACTUAL_USAGE_CDK-dataset.MNTH1_ACTUAL_USAGE_CDK) /
    dataset.MNTH2_ACTUAL_USAGE_CDK)
martineau
  • 119,623
  • 25
  • 170
  • 301
  • What is the desired result if you have an issue like this? If we know what you expect, we can tell you how to treat it. I dont know if you want to create a shortcircuit exit, or process it with with a different value etc – Fallenreaper Jan 31 '20 at 15:32
  • 1
    Did you try something like `if denominator == 0: ; else: `? – mkrieger1 Jan 31 '20 at 15:33
  • Wouldn't zero be false information? The relative increase wasn't zero, after all. From a design view it would be better to keep infinity and disregard those values in further calculations. If you replace them with zero instead, you'd end up not being able to differentiate between actual zeros and fake zeros and making calculations like averages or a trend analysis incorrect. – Nightara Jan 31 '20 at 15:33
  • [Related](https://stackoverflow.com/questions/3733992/determine-whether-a-key-is-present-in-a-dictionary/3734681#3734681) (with respect to handling Exceptions). – martineau Jan 31 '20 at 16:27

1 Answers1

-1

You can try:

try:
    result = (month3 - month2)/month2
except ZeroDivisionError:
    result = 0
  • Bare `except` is [bad practice](https://stackoverflow.com/questions/54948548/what-is-wrong-with-using-a-bare-except). – mkrieger1 Jan 31 '20 at 15:32