1

I have two counters in python: counter1 and counter2. When I try to perform np.nansum on them, one of the fields is ignored because it contains zeros (if i change values to non-zeros the code works fine). Is there any workaround to get all the input keys in the output dict?

counter1 = Counter({'sensitivity': 1.0, 'dice': 1.0, 'specificity': 1.0, 'precision': 1.0, 'c-factor': 0.0})
counter2 = Counter({'sensitivity': 1.0, 'dice': 1.0, 'specificity': 1.0, 'precision': 1.0, 'c-factor': 0.0})
c = np.nansum([counter1, counter2])

the result i get is:

c= Counter({'sensitivity': 2.0, 'specificity': 2.0, 'dice': 2.0, 'precision': 2.0})

to compare, when i do:

counter1 = Counter({'sensitivity': 1.0, 'dice': 1.0, 'specificity': 1.0, 'precision': 1.0, 'c-factor': 0.1})
counter2 = Counter({'sensitivity': 1.0, 'dice': 1.0, 'specificity': 1.0, 'precision': 1.0, 'c-factor': 0.1})
c = np.nansum([counter1, counter2])

i get:

c=Counter({'sensitivity': 2.0, 'specificity': 2.0, 'dice': 2.0, 'precision': 2.0, 'c-factor': 0.2})
Biba
  • 631
  • 9
  • 28

1 Answers1

1

See this post. If you need to update if you want to keep zeros. Try doing:

c=np.nansum(counter1).copy()   #I don't know why you use np.nansum, but you can pass it like this
c.update(np.nansum(counter2))
c
>>Counter({'c-factor': 0.0,
     'dice': 2.0,
     'precision': 2.0,
     'sensitivity': 2.0,
     'specificity': 2.0})
Tarifazo
  • 4,118
  • 1
  • 9
  • 22
  • Thanks so much for the answer, that was the solution I needed. I use the nansum because sometimes c-factor value is a nan (which is correct) and I just want to ignore those values when calculating the sum. – Biba Jan 16 '19 at 07:48