用字符串形象化地可视化 numpy 布尔数组

Pictorially visualise numpy boolean array with strings

假设你有一个 2D numpy 布尔数组,array:

[[ True  True  True  True  True  True]
 [ True  False False False False True]
 [ True  True  True  True  True  True]]

并且您希望用 ██ 替换 True 值和 False 值的空白来表示它们:

  ██████████████
  ██          ██
  ██████████████

我在 chararray 上花费了太多时间,但尝试以下操作无济于事:

chars = np.chararrray(array.shape, unicode=True)
chars[array] = '██'

Chararray,只是一个经常出故障的向后兼容特性。而是遍历数组:

def __str__(self):
    retval = ''
    for row in self.array:
        retval += ''.join(['  ' if i else '██' for i in row])
        retval += '\n'
    return str(self.array)

您建议的解决方案有效,只需要打印得更好:

chars = np.chararray(array.shape, unicode=True)
chars[array] = '██'
print(np.array2string(chars, separator='', formatter={'str_kind': lambda x: x if x else ' '}))

我不确定你是否想去掉括号。

输出:

[[██████]
 [█    █]
 [██████]]

如果你想要没有括号(免责声明:这是懒惰的替换,你可能可以更好地删除它们):

print(np.array2string(chars, separator='', formatter={'str_kind': lambda x: x if x else ' '}).replace(" [","").replace("[","").replace("]",""))

██████
█    █
██████

如果您不喜欢使用 space 字符作为错误条目(这会使定位变得复杂),我建议使用以下稍微简化的版本,从之前的答案中汲取灵感:

def print_bool_array(array, true_char='#', false_char='.'):
    chars = np.empty_like(array, dtype=np.str_)
    chars[array] = true_char
    chars[~array] = false_char
    print(np.array2string(chars, separator='', formatter={'all': lambda x: x}
        ).translate(str.maketrans("", "", " []'")))