繁体   English   中英

Numpy 数组相等 boolean

[英]Numpy array equality boolean

以下两种方法应该产生相同的结果,但似乎它们没有:

方法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:

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

方法2

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

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

比较方法

ann_frac2==ann_frac

Output:

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

好像有点奇怪。 有什么解释吗? 显然,如果只想比较两个不同 arrays 中的数字是否相等,上面的示例表明,即使数字可以相同,创建和存储数字的方式也会产生意想不到的行为。

我认为您正在将 arrays 与不同的维度进行比较。 我猜你想要的是

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)

正确的比较应该是

ann_frac3==ann_frac1

与 output

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

更好的是

(ann_frac3==ann_frac1).all()

与 output

True

暂无
暂无

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

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