Search code examples
pythonarraysnumpychartsascii

Pictorially visualise numpy boolean array with strings


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] = '██'

Solution

  • 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("]",""))
    
    ██████
    █    █
    ██████