NumPy,为什么等式检查对一组对象不起作用?(NumPy, why equality check does not work for an array of objects?)

系统教程 行业动态 更新时间:2024-06-14 17:02:17
NumPy,为什么等式检查对一组对象不起作用?(NumPy, why equality check does not work for an array of objects?)

使用以下对象数组:

a = np.array([[1], [1, 2], [1, 2, 3], [1], [1]], dtype=object) b = np.array([(1,), (1, 2), (1, 2, 3), (1,), (1,)], dtype=object)

以下等式检查不起作用:

a==[1] #array([False, False, False, False, False], dtype=bool) b==(1,) #array([False, False, False, False, False], dtype=bool)

如果我改用字符串:

c = np.array(['[1]', '[1, 2]', '[1, 2, 3]', '[1]', '[1]'])

平等检查有效:

c == '[1]' #array([ True, False, False, True, True], dtype=bool)

为什么数组检查表现如此?

如果我们迭代a或b并执行检查,它也会给出预期的结果:

[i==[1] for i in a] #[True, False, False, True, True] [i==(1,) for i in b] #[True, False, False, True, True]

谢谢!

With the following arrays of objects:

a = np.array([[1], [1, 2], [1, 2, 3], [1], [1]], dtype=object) b = np.array([(1,), (1, 2), (1, 2, 3), (1,), (1,)], dtype=object)

The following equality checks do not work:

a==[1] #array([False, False, False, False, False], dtype=bool) b==(1,) #array([False, False, False, False, False], dtype=bool)

if I use strings instead:

c = np.array(['[1]', '[1, 2]', '[1, 2, 3]', '[1]', '[1]'])

the equality check works:

c == '[1]' #array([ True, False, False, True, True], dtype=bool)

why the array check behaves like that?

If we iterate over a or b and perform the checks it also gives the expected result:

[i==[1] for i in a] #[True, False, False, True, True] [i==(1,) for i in b] #[True, False, False, True, True]

Thank you!

最满意答案

NumPy旨在在许多情况下自动将类似数组的对象视为数组。 在这里,NumPy看到[1]和(1,)是类似数组的对象并应用广播规则。 两侧的长度1轴扩展到另一个对象的相应轴的长度,如果一个对象的尺寸小于另一个对象,则缺少的尺寸在左侧填充,另一个对象的长度在这些尺寸中。 从而,

a == [1]

给出了相同的结果

a == numpy.array([1, 1, 1, 1, 1])

这是一个5 False的数组。

NumPy is designed to automatically treat array-like objects as arrays in many situations. Here, NumPy sees that [1] and (1,) are array-like objects and applies the broadcasting rules. Length-1 axes on either side are expanded out to the length of the other object's corresponding axis, and if one object has less dimensions than the other, missing dimensions are filled in on the left with the other object's lengths in those dimensions. Thus,

a == [1]

gives the same result as

a == numpy.array([1, 1, 1, 1, 1])

which is an array of 5 Falses.

更多推荐

本文发布于:2023-04-21 18:31:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/4ef5b8130f388639eb913fe0df47276d.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:等式   不起作用   对象   NumPy   equality

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!