代码之家  ›  专栏  ›  技术社区  ›  Oxana Verkholyak

为元组数组创建布尔掩码

  •  3
  • Oxana Verkholyak  · 技术社区  · 6 年前

    我有一个二维numpy数组,它的形状为(3,3),dtype=对象,其元素是形式的元组(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,如何使其工作?

    P、 我已经搜索了相关主题,但无法使用任何。。。

    Array of tuples in Python
    Restructuring Array of Tuples
    Apply function to an array of tuples
    Filter numpy array of tuples

    1 回复  |  直到 6 年前
        1
  •  1
  •   Daniel    6 年前

    这里发生的是Python tuples are compared by position. 所以当你这样做的时候

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

    我不知道有什么非黑客的方法可以解决这个问题,并让直接的平等比较发挥作用。如果黑客攻击已经足够,并且您的阵列不是太大,您可以尝试:

    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)
    

    是否有需要元组数组的原因?数组中不能有另一个维度,或者可以使用pandas作为分类变量吗?