Python - print table-like data cleanly
本问题已经有最佳答案,请猛点这里访问。
我有这样的输出
1 2 3 | AB%CD3_SW3Z_1000 uvsec_czrkup_rmplr SeightRveZargrp def_move 35.8% 28.0% 16.2% 120 0.0010 MN%P03_AT%W00_500 uvsec_czrkup_rmplr SeightRveZargrp def_move 28.8% 24.7% 23.4% 94 0.1000 KE_A03_UVA%Q00_100 uvsec_czrkup_rmplr SeightRveZargrp def_move 27.2% 11.8% 3.5% 398 0.010 |
最干净、最优雅的方式是什么
1 2 3 | AB%CD3_SW3Z_1000 uvsec_czrkup_rmplr SeightRveZargrp def_move 35.8% 28.0% 16.2% 120 0.0010 MN%P03_AT%W00_500 uvsec_czrkup_rmplr SeightRveZargrp def_move 28.8% 24.7% 23.4% 94 0.1000 KE_A03_UVA%Q00_100 uvsec_czrkup_rmplr SeightRveZargrp def_move 27.2% 11.8% 3.5% 398 0.010 |
当然,在一般情况下,我会问,假设每行具有相同数量的令牌。我想把各列都联合起来。
我过去曾为这种类型的应用程序使用过prettyTables和此函数:
1 2 3 4 5 | def format_df(df): table = PrettyTable([''] + list(df.columns)) for row in df.itertuples(): table.add_row(row) return str(table) |
使用输入的完整示例如下:
1 2 3 4 5 6 7 8 9 10 11 | import pandas as pd from prettytable import PrettyTable def format_df(df): table = PrettyTable([''] + list(df.columns)) for row in df.itertuples(): table.add_row(row) return str(table) df = pd.read_clipboard(header=None) # No header provided on example input print(format_df(df)) |
这将生成以下输出。由于示例数据中没有提供标题,因此标题的命名不正确:
1 2 3 4 5 6 7 | +---+--------------------+--------------------+-----------------+----------+-------+-------+-------+-----+-------+ | | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | +---+--------------------+--------------------+-----------------+----------+-------+-------+-------+-----+-------+ | 0 | AB%CD3_SW3Z_1000 | uvsec_czrkup_rmplr | SeightRveZargrp | def_move | 35.8% | 28.0% | 16.2% | 120 | 0.001 | | 1 | MN%P03_AT%W00_500 | uvsec_czrkup_rmplr | SeightRveZargrp | def_move | 28.8% | 24.7% | 23.4% | 94 | 0.1 | | 2 | KE_A03_UVA%Q00_100 | uvsec_czrkup_rmplr | SeightRveZargrp | def_move | 27.2% | 11.8% | 3.5% | 398 | 0.01 | +---+--------------------+--------------------+-----------------+----------+-------+-------+-------+-----+-------+ |
一种方法是使用