使用prettytable美化dataframe输出的表格

文章目录

  • Prettytable简单示例
  • 输出DataFrame为PrettyTable

Prettytable简单示例

prettytable的简单应用:

from prettytable import PrettyTable

pre_table = PrettyTable()
pre_table.title = '这是标题'
pre_table.field_names = ["列1", "列2", "列3", "列4"]
pre_table.add_row(["值1", 1, 2, 3])
pre_table.add_row(["值2", 1, 2, 3])
pre_table.add_row(["值3", 1, 2, 3])
print(pre_table)

得到结果:

+-----------------------+
|        这是标题       |
+-----+-----+-----+-----+
| 列1 | 列2 | 列3 | 列4 |
+-----+-----+-----+-----+
| 值1 |  1  |  2  |  3  |
| 值2 |  1  |  2  |  3  |
| 值3 |  1  |  2  |  3  |
+-----+-----+-----+-----+

输出DataFrame为PrettyTable

输出的思路比较简单:from_csv接收一个dataframe的csv的字节流即可

from prettytable import from_csv
import pandas as pd
import numpy as np
from io import StringIO


def export_df_to_table(dataframe):
    """工具函数:将dataframe的表格输出为 prettytable 表示的表格"""
    output = StringIO()
    dataframe.to_csv(output)
    output.seek(0)
    string_value = from_csv(output)
    return string_value


def main():
    dataframe = pd.DataFrame(np.random.randint(0, 10, size=(10, 3)), columns=["col1", "col2", "col3"])
    string_value = export_df_to_table(dataframe)
    print(string_value)


if __name__ == '__main__':
    main()

得到结果:

+---+------+------+------+
|   | col1 | col2 | col3 |
+---+------+------+------+
| 0 |  1   |  6   |  5   |
| 1 |  6   |  1   |  4   |
| 2 |  2   |  7   |  1   |
| 3 |  4   |  0   |  7   |
| 4 |  0   |  6   |  4   |
| 5 |  7   |  4   |  5   |
| 6 |  8   |  9   |  7   |
| 7 |  9   |  6   |  1   |
| 8 |  5   |  8   |  6   |
| 9 |  7   |  7   |  5   |
+---+------+------+------+

你可能感兴趣的:(python,python,pandas,开发语言)