3

我有一个形状为 (3, 3) 和 dtype=object 的 2D numpy 数组,其元素是 (str, str, float) 形式的元组。

template = ('Apple', 'Orange', 5.0)
my_array = np.array([None] * 9).reshape((3,3))

for i in range(my_array.shape[0]):
    for j in range(my_array.shape[1]):
        my_array[i, j] = template

但是当我尝试获取布尔掩码时

print(my_array == template)

答案全是假的

[[False False False]
 [False False False]
 [False False False]]

然而,逐元素比较仍然有效

print(my_array[0,0] == template) # This prints True

为什么布尔掩码返回所有 False 以及如何使其工作?

PS我已经搜索了相关主题,但无法使用任何...

Python中的元组数组
重构元组数组
将函数应用于元组数组
过滤元组的numpy数组

4

1 回答 1

1

这里发生的是,在 Python 中,元组是按位置进行比较的。 所以当你这样做时

my_array == template

你实际上在做什么(按行)是:

('Apple', 'Orange', 5.0) == 'Apple'
('Apple', 'Orange', 5.0) == 'Orange'
('Apple', 'Orange', 5.0) == 5.0

要验证是否是这种情况,请尝试使用以下示例进行试验:

>>> other_array = np.array(['Apple', 'Orange', 5.0] * 3).reshape(3,3)
>>> other_array
array([['Apple', 'Orange', '5.0'],
       ['Apple', 'Orange', '5.0'],
       ['Apple', 'Orange', '5.0']], dtype='<U6')
>>> other_array == template
array([[ True,  True,  True],
       [ True,  True,  True],
       [ True,  True,  True]])

我不知道有任何非骇客的方式来解决这个问题并获得直接的平等比较工作。如果 hack 就足够了,并且您的数组不是太大,您可以尝试:

mask = np.array(list(map(lambda x: x == template,
                         my_array.flatten()))).reshape(my_array.shape)

或者

mask = np.array([x == template for x in my_array.flatten()]).reshape(my_array.shape)

你需要一个元组数组有什么原因吗?你不能在你的数组中有另一个维度,或者可能使用熊猫作为你的分类变量吗?

于 2018-04-22T12:15:20.010 回答