当前位置:  开发笔记 > 编程语言 > 正文

print(tabulate(...))to pretty print multiIndex pandas?

如何解决《print(tabulate())toprettyprintmultiIndexpandas?》经验,为你挑选了1个好方法。

说我有一个熊猫数据框:

import numpy as np
import pandas as pd
from tabulate import tabulate

A = pd.DataFrame(np.random.randint(0,10,(3,6)), index= ['uno', 'dos', 'tres'])
A.columns = ['A','B','C','D','E','F']
A.index.names = ['type']
A.columns.names= ['group']

h = [A.index.names[0] +'/'+ A.columns.names[0]] + list(A.columns)
print(tabulate(A, headers= h, tablefmt= 'grid'))

这使:

+--------------+-----+-----+-----+-----+-----+-----+
| type/group   |   A |   B |   C |   D |   E |   F |
+==============+=====+=====+=====+=====+=====+=====+
| uno          |   3 |   1 |   6 |   0 |   7 |   0 |
+--------------+-----+-----+-----+-----+-----+-----+
| dos          |   9 |   5 |   3 |   0 |   6 |   6 |
+--------------+-----+-----+-----+-----+-----+-----+
| tres         |   6 |   7 |   4 |   6 |   8 |   4 |
+--------------+-----+-----+-----+-----+-----+-----+

现在添加一个图层:

iterable = [['A', 'B'], ['AA', 'BB', 'CC']]
A.columns = pd.MultiIndex.from_product(iterable,
                                       names= ['group', 'subgroup'])
A.index.names = ['type']

将使用打印声明给出:

group     A        B      
subgroup AA BB CC AA BB CC
type                      
uno       3  1  6  0  7  0
dos       9  5  3  0  6  6
tres      6  7  4  6  8  4

通常,这在诸如pweave的文档上不能很好地呈现.

我如何使用print(tabulate(...)),例如我将每个组和子组显示在单独的行上?

谢谢



1> unutbu..:

使用表格版本0.8.1或更高版本时,

import numpy as np
import pandas as pd
from tabulate import tabulate

A = pd.DataFrame(np.random.randint(0,10,(3,6)), index= ['uno', 'dos', 'tres'])
A.columns = ['A','B','C','D','E','F']
A.index.names = ['type']
A.columns.names= ['group']

iterable = [['A', 'B'], ['AA', 'BB', 'CC']]
A.columns = pd.MultiIndex.from_product(iterable, names= ['group', 'subgroup'])

h = [A.index.names[0] +'/'+ A.columns.names[0]] + list(map('\n'.join, A.columns.tolist()))
print(tabulate(A, headers= h, tablefmt= 'grid'))

产量

+--------------+------+------+------+------+------+------+
| type/group   |    A |    A |    A |    B |    B |    B |
|              |   AA |   BB |   CC |   AA |   BB |   CC |
+==============+======+======+======+======+======+======+
| uno          |    8 |    4 |    3 |    3 |    4 |    2 |
+--------------+------+------+------+------+------+------+
| dos          |    1 |    1 |    1 |    9 |    8 |    9 |
+--------------+------+------+------+------+------+------+
| tres         |    0 |    4 |    3 |    6 |    1 |    7 |
+--------------+------+------+------+------+------+------+

推荐阅读
拾味湖
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有