Pictorially visualise numpy boolean array with strings

Viewed 134

Say you have a 2D numpy array of bools, array:

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

And you wish to represent them pictorially with ██ replacing the True values and whitespace for the False values:

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

I've spent too much time with the chararray to no avail trying things like:

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

Your suggested solution works, only need to print it nicer:

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

I am not sure if you want to get rid of the brackets or not though.

output:

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

In case you wanted without brackets (disclaimer: this is lazy replacement, you probably can do a better job removing them):

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

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

Chararray, is only a backwards compatibility feature that breaks down often. Instead iterate through the array:

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

If you're not married to the use of a space character for the false entries (which complicates positioning), I suggest the following slightly simplified version, taking inspiration from the previous answers:

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("", "", " []'")))
Related