Python制表:具有多个带有合并单元格的标题

kik*_*iki 10 python header tabulate

有没有办法在 python 中指定带有合并单元格的多个标题?

示例数据集:

from tabulate import tabulate

cols = ["ID", "Config\nA", "Config\nB", "Config\nC", "Config\nD", "Oth"]
rows = [[ "0x0", "2", "0", "0", "4", "3"],
        [ "0x1", "0", "0", "0", "0", "4"],
        [ "0x2", "0", "2", "0", "1", "5"]]

print(tabulate(rows, headers=cols,tablefmt="pretty"))
Run Code Online (Sandbox Code Playgroud)

表格的当前输出:

 +-----+--------+--------+--------+--------+--------+
 | ID  | Config | Config | Config | Config |   Oth  |
 |     |   A    |   B    |   C    |   D    |        |
 +-----+--------+--------+--------+--------+--------+
 | 0x0 |   2    |   0    |   0    |   4    |   3    |
 | 0x1 |   0    |   0    |   0    |   0    |   4    |
 | 0x2 |   0    |   1    |   0    |   1    |   5    |
 +-----+--------+--------+--------+--------+--------+
Run Code Online (Sandbox Code Playgroud)

期望的输出:

 +-----+---+---+---+---+-----+
 | ID  |     Config    | Oth |
 +     +---+---+---+---+     |
 |     | A | B | C | D |     |
 +-----+---+---+---+---+-----+
 | 0x0 | 2 | 0 | 0 | 4 |  3  |
 | 0x1 | 0 | 0 | 0 | 0 |  4  |
 | 0x2 | 0 | 2 | 0 | 1 |  5  |
 +-----+---+---+---+---+-----+
Run Code Online (Sandbox Code Playgroud)

Mar*_*ell 5

我不完全确定您将使用该表做什么,但我也许建议切换到 Pandas 库。他们对各种数据标签都有广泛的支持。

import pandas as pd

column_names = pd.DataFrame([["Config", "A"], 
                             ["Config", "B"], 
                             ["Config", "C"], 
                             ["Config", "D"], 
                             ["0th", ""]], 
                             columns=["ID", ""])

rows = [["2", "0", "0", "4", "3"],
        ["0", "0", "0", "0", "4"],
        ["0", "2", "0", "1", "5"]]

columns = pd.MultiIndex.from_frame(column_names)
index = ["0x0", "0x1", "0x2"]

df = pd.DataFrame(rows, columns=columns, index=index)
display(df)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述