Search code examples
pythonnumpypretty-printtabulate

python tabulate: display blank cell for specific values


I have this numpy array

import numpy as np
from tabulate import tabulate

data  = np.array([[1,2], [3,4]])
data2 = tabulate(data, tablefmt='fancy_grid')
print(data2)

╒═══╤═══╕
│ 1 │ 2 │
├───┼───┤
│ 3 │ 4 │
╘═══╧═══╛

I'm interested in a cleaner display of my table while ignoring values I'm not interested in. How can I print blank cells for specific values? For example, blanks for all 2 values in the array, like this:

╒═══╤═══╕
│ 1 │   │
├───┼───┤
│ 3 │ 4 │
╘═══╧═══╛

Solution

  • You can convert to 'U' or 'S' dtype and explicitly replace the special values with '':

    from tabulate import tabulate                
     
    data  = np.array([[1,2], [3,4]])             
    data2 = tabulate(np.where(data==2,'',data.astype('U')), tablefmt='fancy_grid') 
    print(data2)                                                                  
    ╒═══╤═══╕
    │ 1 │   │
    ├───┼───┤
    │ 3 │ 4 │
    ╘═══╧═══╛