1. 引言
如果能够将我们的无序数据快速组织成更易读的格式,对于数据分析非常有帮助。 Python 提供了将某些表格数据类型轻松转换为格式良好的纯文本表格的能力,这就是 tabulate
库。
2. 准备工作
安装tabulate库:
安装tabulate库非常容易,使用pip即可安装,代码如下:
pip install tabulate
导入tabulate函数:
接着我们需要导入我们需要的tabulte函数,如下:
from tabulate import tabulate
准备工作做好后,接下来我们来举个栗子。
3. 举个栗子
3.1 使用list生成表格
接着我们假设我们有以下数据:
table = [["First Name", "Last Name", "Age"], ["John", "Smith", 39], ["Mary", "Jane", 25], ["Jennifer", "Doe", 28]]
接着我们可以使用 tabulate
函数将上述数据组织成一个更易读的表格形式,代码如下:
print(tabulate(table))
结果如下:
由于上述list
中的第一个列表包含每列的名称,我们可以使用以下参数将列名单独显示出来,代码如下:
print(tabulate(table, headers="firstrow"))
结果如下:
tabulate
函数还包提供一个 tablefmt
参数,它允许我们进一步改进表格的外观,
代码如下:
print(tabulate(table, headers="firstrow", tablefmt="grid"))
结果如下:
相比grid,我更喜欢对 tablefmt 使用fancy_grid参数,其表现形式如下:
print(tabulate(table, headers="firstrow", tablefmt="fancy_grid"))
结果如下:
3.2 使用dict生成表格
当然,在Python
中我们也可以使用字典来生成相应的表格。
代码如下:
info = {"First Name": ["John", "Mary", "Jennifer"], "Last Name": ["Smith", "Jane", "Doe"], "Age": [39, 25, 28]}
在字典的情况下,键通常是列的标题,值将是这些列的元素取值。我们通常通过传递“keys”作为 headers 参数的参数来指定键是表格的标题:
print(tabulate(info, headers="keys"))
输出如下:
当然,此时我们也可以使用 tablefmt 参数来改善表格的外观,代码如下:
print(tabulate(info, headers="keys", tablefmt="fancy_grid"))
输出如下:
3.3 增加索引列
进一步来说,我们还可以使用showindex
参数来向表格中添加索引列,代码如下:
3.4 缺失值处理
如果我们从字典中移走’Jennifer
’,此时我们的表格将会包含一个空白单元格,代码如下:
print(tabulate({"First Name": ["John", "Mary"], "Last Name": ["Smith", "Jane", "Doe"], "Age": [39, 25, 28]}, headers="keys", tablefmt="fancy_grid"))
输出如下:
有时候,我们觉得缺失值用空白格表示不太美观,此时我们可以设置默认值来显示,代码如下:
print(tabulate({"First Name": ["John", "Mary"], "Last Name": ["Smith", "Jane", "Doe"], "Age": [39, 25, 28]}, headers="keys", tablefmt="fancy_grid"))
结果如下:
到此这篇关于Python中创建表格详细的文章就介绍到这了,更多相关Python中创建表格内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!