使用以下对象数组:
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.
更多推荐
发布评论