简体   繁体   English

Numpy 数组相等 boolean

[英]Numpy array equality boolean

The following two approaches should yield an identical result, but it seems they do not:以下两种方法应该产生相同的结果,但似乎它们没有:

Approach 1 :方法1

#Generate an array with 12 annual fractions corresponding to each month
ann_frac = np.arange(1,13,1).reshape([12,1])
ann_frac = ann_frac[:,0]/12

Output: Output:

array([0.08333333, 0.16666667, 0.25      , 0.33333333, 0.41666667,
       0.5       , 0.58333333, 0.66666667, 0.75      , 0.83333333,
       0.91666667, 1.        ])

Approach 2 :方法2

i = np.arange(1,13,1)
ann_frac2 = (i/12).reshape([12,1])

Output: Output:

array([[0.08333333],
       [0.16666667],
       [0.25      ],
       [0.33333333],
       [0.41666667],
       [0.5       ],
       [0.58333333],
       [0.66666667],
       [0.75      ],
       [0.83333333],
       [0.91666667],
       [1.        ]])

Comparing approaches :比较方法

ann_frac2==ann_frac

Output: Output:

array([[False],
       [False],
       [False],
       [False],
       [False],
       [False],
       [False],
       [False],
       [False],
       [False],
       [False],
       [False]])

A bit strange it seems.好像有点奇怪。 Any explanation?有什么解释吗? Obviously, if one just wants to compare numbers in two different arrays for equlity, the example above demonstrates that even though the numbers can be identical, the way the numbers were created and stored can produce an unexpected behaviour.显然,如果只想比较两个不同 arrays 中的数字是否相等,上面的示例表明,即使数字可以相同,创建和存储数字的方式也会产生意想不到的行为。

I think you are comparing arrays with different dimensionality.我认为您正在将 arrays 与不同的维度进行比较。 What I guess you want is我猜你想要的是

ann_frac = np.arange(1,13,1).reshape([12,1])
ann_frac1 = ann_frac[:,0]/12
i = np.arange(1,13,1)
ann_frac2 = (i/12).reshape([12,1])
ann_frac3 = (i/12).reshape(12)

and the correct comparison should be正确的比较应该是

ann_frac3==ann_frac1

with output与 output

array([ True,  True,  True,  True,  True,  True,  True,  True,  True,
    True,  True,  True])

Even better would be更好的是

(ann_frac3==ann_frac1).all()

with output与 output

True

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM