【问题标题】:print multi-index dataframe with tabulate使用表格打印多索引数据框
【发布时间】:2021-11-18 02:01:49
【问题描述】:

如何打印一个多索引数据框,如下所示:

import numpy as np
import tabulate
import pandas as pd


df = pd.DataFrame(np.random.randn(4, 3),
                  index=pd.MultiIndex.from_product([["foo", "bar"],
                                                    ["one", "two"]]),
                  columns=list("ABC"))

以便 Multindex 的两个级别显示为单独的列,与 pandas 本身打印它的方式非常相似:

In [16]: df
Out[16]: 
                A         B         C
foo one -0.040337  0.653915 -0.359834
    two  0.271542  1.328517  1.704389
bar one -1.246009  0.087229  0.039282
    two -1.217514  0.721025 -0.017185

但是,像这样列出打印:

In [28]: print(tabulate.tabulate(df, tablefmt="github", headers="keys", showindex="always"))
|                |          A |         B |          C |
|----------------|------------|-----------|------------|
| ('foo', 'one') | -0.0403371 | 0.653915  | -0.359834  |
| ('foo', 'two') |  0.271542  | 1.32852   |  1.70439   |
| ('bar', 'one') | -1.24601   | 0.0872285 |  0.039282  |
| ('bar', 'two') | -1.21751   | 0.721025  | -0.0171852 |

【问题讨论】:

  • 我觉得没问题。你有什么问题?

标签: python pandas tabulate


【解决方案1】:

MultiIndexes 在内部由元组表示,因此 tabulate 向您展示了正确的东西。

如果你想要柱状显示,最简单的方法是先reset_index

print(tabulate.tabulate(df.reset_index().rename(columns={'level_0':'', 'level_1': ''}), tablefmt="github", headers="keys", showindex=False))

输出:

|     |     |         A |         B |         C |
|-----|-----|-----------|-----------|-----------|
| foo | one | -0.108977 |  2.03593  |  1.11258  |
| foo | two |  0.65117  | -1.48314  |  0.391379 |
| bar | one | -0.660148 |  1.34875  | -1.10848  |
| bar | two |  0.561418 |  0.762137 |  0.723432 |

或者,您可以将 MultiIndex 重新设计为单个索引:

df2 = df.copy()
df2.index = df.index.map(lambda x: '|'.join(f'{e:>5} ' for e in x))

print(tabulate.tabulate(df2.rename_axis('index'), tablefmt="github", headers="keys", showindex="always"))

输出:

| index      |         A |         B |         C |
|------------|-----------|-----------|-----------|
| foo |  one | -0.108977 |  2.03593  |  1.11258  |
| foo |  two |  0.65117  | -1.48314  |  0.391379 |
| bar |  one | -0.660148 |  1.34875  | -1.10848  |
| bar |  two |  0.561418 |  0.762137 |  0.723432 |

【讨论】:

  • 是的,您显示的第一个表示似乎是最接近的。我可以找到一种方法来删除重置索引中的冗余行以匹配熊猫显示。我真的很喜欢 pandas 简洁的展示方式,非常适合展示。
猜你喜欢
  • 1970-01-01
  • 2020-03-19
  • 1970-01-01
  • 2017-07-09
  • 2017-03-28
  • 1970-01-01
  • 1970-01-01
  • 2014-08-29
相关资源
最近更新 更多