一、簡介
pythontabulate 是一款基於 Python 的包,它用於將各種數據以美觀的表格形式列印(ASCII,Markdown,HTML等)。如果你需要將數據格式化為表格數據,這可能是您需要的最後一個庫。它具有許多功能,例如:自定義表頭,對其方式,精確小數位數,列寬以及列優先順序等。它還支持對字典和數組等數據類型進行表格化。該庫的安裝方法很容易:
pip3 install tabulate
二、表格的不同格式
首先讓我們看看該庫可以在三種格式中格式化表格:
- ASCII格式:
+----+-------+-----------+ | id | name | age | +----+-------+-----------+ | 1 | Alice | 20 | | 2 | Bob | 30 | +----+-------+-----------+
- Markdown 格式:
| id | name | age | |----|-------|-----------| | 1 | Alice | 20 | | 2 | Bob | 30 |
- HTML 格式:
| id | name | age |
|---|---|---|
| 1 | Alice | 20 |
| 2 | Bob | 30 |
三、使用 pythontabulate
為了使用用 pythontabulate 列印表格,我們必須先將要列印的數據存儲為數組或字典形式:
from tabulate import tabulate data = [['Alice', 20], ['Bob', 30]] headers = ['name', 'age'] print(tabulate(data, headers, tablefmt='psql'))
這將生成以下的表格:
+-------+-----+ | name | age | |-------+-----| | Alice | 20 | | Bob | 30 | +-------+-----+
在這個例子中,我們傳遞了數據和標題參數,然後使用 psqsl 表格格式。該 tablefmt 參數可以是「plain」、「simple」、「github」、「grid」等格式。
四、自定義列優先順序、對齊方式和格式
除了標題和數據外,我們還可以設置列的對齊方式和列的格式。下面是一個包括所有選項的示例:
data = [
['Alice', 20, 123456.789],
['Bob is really cool', 30, 234567.890],
['Charlie', 40, 345678.901]
]
headers = ['name', 'age', 'num']
print(tabulate(data, headers=headers, tablefmt="psql", numalign="decimal", stralign="center", floatfmt=".2f"))
這將生成以下的表格:
+------------------+-----+------------+ | name | age | num | |------------------+-----+------------| | Alice | 20 | 123456.79 | | Bob is really cool| 30 | 234567.89 | | Charlie | 40 | 345678.90 | +------------------+-----+------------+
在此示例中,我們在表單中使用標題和數據進行表格化,然後使用 psqsl 表格格式,並使用 numalign、stralign 和 floatfmt 參數進行對齊和格式設置。使用 numalign 和 stralign 參數,您可以分別設置數字和字元串的對齊方式。floatfmt 參數用于格式化表格中的浮點數。
五、其他示例
有關更多示例,請參閱以下代碼和結果:
# 字典 row 方式列印
data = [{'name': 'Alice', 'age': 20}, {'name': 'Bob', 'age': 30}]
print(tabulate(data, headers='keys', tablefmt='psql'))
# 列印 CSV 格式文件
import csv
with open('data.csv') as f:
reader = csv.reader(f)
data = [row for row in reader]
print(tabulate(data, headers='firstrow'))
# 縱向列印數據
data = [['Alice', 20], ['Bob', 30]]
print(tabulate(data, tablefmt='plain', showindex=True))
# 簡單數據表
data = [['Alice', 20], ['Bob', 30]]
print(tabulate(data))
# 沒有表頭的簡單表格式
data = [['Alice', 20], ['Bob', 30]]
print(tabulate(data, headers=['Name', 'Age'], tablefmt='plain'))
pythontabulate是一款十分實用的Python庫,可以方便快捷地將數據格式化為美觀的表格。這為數據分析提供了便利和可視化的解決方法。記得去官網查看更多內容。
原創文章,作者:PMHV,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/149650.html
微信掃一掃
支付寶掃一掃