np.nansum忽略计数器中的零

时间:2019-01-15 15:02:07

标签: python-3.x numpy

我在python中有两个计数器:counter1和counter2。当我尝试对它们执行np.nansum时,将忽略其中一个字段,因为它包含零(如果我将值更改为非零,则代码可以正常工作)。是否有任何解决方法可将所有输入键输入到输出字典中?

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])

我得到的结果是:

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

比较,当我这样做:

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])

我得到:

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

1 个答案:

答案 0 :(得分:1)

请参见this post。如果您想保留零,则需要update。尝试做:

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})