【问题标题】:python tabulate: display blank cell for specific valuespython制表:显示特定值的空白单元格
【发布时间】:2020-11-02 02:21:00
【问题描述】:

我有这个 numpy 数组

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 │
╘═══╧═══╛

我对更简洁的表格显示感兴趣,而忽略了我不感兴趣的值。如何打印特定值的空白单元格?例如,数组中所有 2 个值的空白,如下所示:

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

【问题讨论】:

  • 您可以编写一个包装函数,将 numpy 数组转换为列表列表,然后手动将某个元素的所有更改为 " "

标签: python numpy pretty-print tabulate


【解决方案1】:

您可以转换为'U''S' dtype 并用'' 显式替换特殊值:

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 │
╘═══╧═══╛

【讨论】:

  • 太棒了,从源头修改。成功了,谢谢!
猜你喜欢
  • 2022-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多