Python tablib
last modified November 29, 2026 Python 3.15
In this article we show how to work with tabular data using the tablib library.
tablib is a format-agnostic library for tabular data. Its central
object, Dataset, holds rows with optional headers and a title. A
dataset can be built in code or loaded from a file, modified, and exported to
many formats: CSV, TSV, JSON, YAML, XLSX, ODS, HTML, reStructuredText, LaTeX,
and SQL. A Databook groups several datasets, for example the
sheets of a workbook.
The core library handles CSV, JSON, and the text formats. Excel and YAML need extras. The examples use tablib 3.10.
$ pip install "tablib[xlsx,yaml]"
The first dataset
We create an empty dataset, set its headers, and append rows.
import tablib ds = tablib.Dataset() ds.headers = ['first_name', 'last_name', 'occupation'] ds.append(['John', 'Doe', 'gardener']) ds.append(['Adam', 'Brown', 'programmer']) ds.append(['Tom', 'Holland', 'teacher']) print(ds) print(ds.height, ds.width)
Each row is a list or tuple with one value per header. Printing a dataset shows
it as a simple text table. The height attribute is the number of
rows and width the number of columns.
$ python first_dataset.py first_name|last_name|occupation ----------|---------|---------- John |Doe |gardener Adam |Brown |programmer Tom |Holland |teacher 3 3
Creating datasets
The Dataset constructor takes the rows as positional arguments and
the headers and title as keyword arguments. The dict property
converts a dataset to and from a list of dictionaries.
import tablib
rows = [('Lucia', 'sales', 3100), ('John', 'it', 4200),
('Adam', 'sales', 2800)]
ds = tablib.Dataset(*rows, headers=['name', 'dept', 'salary'],
title='staff')
print(ds.title)
print(ds.dict)
records = [{'name': 'Jane', 'dept': 'it', 'salary': 4200},
{'name': 'Peter', 'dept': 'hr', 'salary': 2600}]
ds2 = tablib.Dataset()
ds2.dict = records
print(ds2.headers)
print(ds2)
Reading ds.dict returns one dictionary per row. Assigning a list
of dictionaries to dict fills an empty dataset; the headers are
taken from the keys of the first dictionary.
$ python create.py
staff
[{'name': 'Lucia', 'dept': 'sales', 'salary': 3100}, {'name': 'John', 'dept': 'it', 'salary': 4200}, {'name': 'Adam', 'dept': 'sales', 'salary': 2800}]
['name', 'dept', 'salary']
name |dept|salary
-----|----|------
Jane |it |4200
Peter|hr |2600
Rows and columns
An integer index selects a row and a header name selects a column. Iterating over a dataset yields the rows as tuples.
import tablib
ds = tablib.Dataset(
('Lucia', 'sales', 3100), ('John', 'it', 4200),
('Adam', 'sales', 2800), ('Jane', 'it', 4200),
headers=['name', 'dept', 'salary'])
print(ds[0])
print(ds[-1])
print(ds[1:3])
print(ds['name'])
print(ds.get_col(2))
print(sum(ds['salary']))
for name, dept, salary in ds:
print(f'{name:6} {dept:6} {salary:>5}')
Rows support negative indexes and slices. A column is returned as a list, so
we can pass it to functions such as sum. The
get_col method selects a column by its position. Each row tuple is
unpacked in the for loop.
$ python rows_cols.py
('Lucia', 'sales', 3100)
('Jane', 'it', 4200)
[('John', 'it', 4200), ('Adam', 'sales', 2800)]
['Lucia', 'John', 'Adam', 'Jane']
[3100, 4200, 2800, 4200]
14300
Lucia sales 3100
John it 4200
Adam sales 2800
Jane it 4200
Inserting and removing data
Besides append, a dataset has methods to insert rows and columns
at a position and to remove them.
import tablib
ds = tablib.Dataset(
('Lucia', 'sales', 3100), ('John', 'it', 4200),
('Adam', 'sales', 2800),
headers=['name', 'dept', 'salary'])
ds.insert(0, ('Peter', 'hr', 2600))
ds.append_col([1990, 1985, 1979, 1993], header='born')
ds.insert_col(1, ['P', 'L', 'J', 'A'], header='initial')
print(ds)
del ds['initial']
removed = ds.pop()
print(removed)
del ds[0]
print(ds)
The insert method adds a row at the given index. The
append_col and insert_col methods add a column with a
list of values, one per row, and a header. The del statement
removes a column by name or a row by index, and pop removes and
returns the last row.
$ python modify.py
name |initial|dept |salary|born
-----|-------|-----|------|----
Peter|P |hr |2600 |1990
Lucia|L |sales|3100 |1985
John |J |it |4200 |1979
Adam |A |sales|2800 |1993
('Adam', 'sales', 2800, 1993)
name |dept |salary|born
-----|-----|------|----
Lucia|sales|3100 |1985
John |it |4200 |1979
Computed columns
Instead of a list of values, append_col accepts a function. tablib
calls it for each row and stores the result in the new column.
import tablib
ds = tablib.Dataset(
('Lucia', 'sales', 3100), ('John', 'it', 4200),
('Adam', 'sales', 2800), ('Jane', 'it', 4200),
headers=['name', 'dept', 'salary'])
def bonus(row):
rate = 0.10 if row[1] == 'sales' else 0.05
return round(row[2] * rate)
ds.append_col(bonus, header='bonus')
print(ds)
ds.append(('Peter', 'hr', 2600))
print(ds[-1])
The bonus function receives a row and returns 10 % of the salary
for sales and 5 % for the others. The column is a dynamic column: when we
append another row with only three values, tablib computes the bonus for it as
well.
$ python computed.py
name |dept |salary|bonus
-----|-----|------|-----
Lucia|sales|3100 |310
John |it |4200 |210
Adam |sales|2800 |280
Jane |it |4200 |210
('Peter', 'hr', 2600, 130)
Sorting and subsets
The sort method returns a new dataset sorted by a column; the
original is not changed. The subset method selects some rows and
columns.
import tablib
ds = tablib.Dataset(
('Lucia', 'sales', 3100), ('John', 'it', 4200),
('Adam', 'sales', 2800), ('Jane', 'it', 4200),
('Peter', 'hr', 2600),
headers=['name', 'dept', 'salary'])
by_name = ds.sort('name')
print(by_name['name'])
by_salary = ds.sort('salary', reverse=True)
print(by_salary)
print(ds['name'])
top = ds.subset(rows=[0, 1], cols=['name', 'salary'])
print(top)
We sort by name, and by salary in descending order. The sort is stable, so
John and Jane, who have the same salary, keep their original order. The last
print of the names shows that ds itself is still in
the input order. The subset method takes a list of row indexes and
a list of column names.
$ python sorting.py ['Adam', 'Jane', 'John', 'Lucia', 'Peter'] name |dept |salary -----|-----|------ John |it |4200 Jane |it |4200 Lucia|sales|3100 Adam |sales|2800 Peter|hr |2600 ['Lucia', 'John', 'Adam', 'Jane', 'Peter'] name |salary -----|------ Lucia|3100 John |4200
Filtering with tags
Rows can carry tags. The filter method returns a new dataset with
the rows that have the given tags.
import tablib
ds = tablib.Dataset(headers=['name', 'dept', 'salary'])
ds.append(('Lucia', 'sales', 3100), tags=['sales', 'senior'])
ds.append(('John', 'it', 4200), tags=['it', 'senior'])
ds.append(('Adam', 'sales', 2800), tags=['sales'])
ds.append(('Jane', 'it', 4200), tags=['it'])
print(ds.filter('sales'))
print()
print(ds.filter(['it', 'senior']))
print()
print(len(ds))
Tags are passed to append as a list. Filtering by one tag selects
the rows with that tag. With a list of tags, a row is selected when it has any
of them: John is both it and senior, and Jane is
it. The original dataset still has four rows.
$ python tags.py name |dept |salary -----|-----|------ Lucia|sales|3100 Adam |sales|2800 name |dept |salary -----|-----|------ Lucia|sales|3100 John |it |4200 Jane |it |4200 4
Formatting columns
The add_formatter method registers a function that converts the
values of a column when the dataset is exported.
import datetime
import tablib
ds = tablib.Dataset(headers=['name', 'height', 'born'])
ds.append(['John Doe', 174.5, datetime.date(1990, 1, 1)])
ds.append(['Roger Roe', 182.66, datetime.date(1995, 5, 15)])
ds.add_formatter('height', lambda v: f'{v:.1f} cm')
ds.add_formatter('born', lambda v: v.strftime('%d.%m.%Y'))
print(ds)
print(ds['height'])
print(ds.export('csv'), end='')
The formatters add a unit to the height and print the date in the day, month,
year order. They are applied only on export, not when the dataset is printed or
a column is read: the printed table and ds['height'] still show
the raw values, while the CSV output is formatted.
$ python formatting.py name |height|born ---------|------|---------- John Doe |174.5 |1990-01-01 Roger Roe|182.66|1995-05-15 [174.5, 182.66] name,height,born John Doe,174.5 cm,01.01.1990 Roger Roe,182.7 cm,15.05.1995
Exporting to text formats
The export method returns the dataset in a given format. Text
formats return a string.
import tablib
ds = tablib.Dataset(
('Lucia', 'sales', 3100), ('John', 'it', 4200),
headers=['name', 'dept', 'salary'], title='staff')
print(ds.export('csv'))
print(ds.export('json'))
print(ds.export('yaml'))
print(ds.export('rst'))
print(ds.export('sql'))
The JSON export is a list of objects keyed by the headers. The
rst format produces a reStructuredText table and the
sql format INSERT statements that use the title of
the dataset as the table name.
$ python export_text.py
name,dept,salary
Lucia,sales,3100
John,it,4200
[{"name": "Lucia", "dept": "sales", "salary": 3100}, {"name": "John", "dept": "it", "salary": 4200}]
- {name: Lucia, dept: sales, salary: 3100}
- {name: John, dept: it, salary: 4200}
===== ===== ======
name dept salary
===== ===== ======
Lucia sales 3100
John it 4200
===== ===== ======
INSERT INTO staff (name,dept,salary) VALUES ('Lucia', 'sales', 3100);
INSERT INTO staff (name,dept,salary) VALUES ('John', 'it', 4200);
Writing files
To create a file, we write the exported data. Binary formats, such as XLSX, return bytes and need a file opened in binary mode.
import tablib
ds = tablib.Dataset(
('Lucia', 'sales', 3100), ('John', 'it', 4200),
('Adam', 'sales', 2800), ('Jane', 'it', 4200),
headers=['name', 'dept', 'salary'], title='staff')
with open('staff.csv', 'w', newline='') as f:
f.write(ds.export('csv'))
with open('staff.xlsx', 'wb') as f:
f.write(ds.export('xlsx'))
with open('staff.html', 'w') as f:
f.write(ds.export('html'))
print(open('staff.csv').read(), end='')
print(open('staff.html').read())
The CSV file is opened with newline='', because the CSV export
already contains the line endings; otherwise Windows would write an extra
carriage return. The HTML export is one line with a table
element.
$ python export_files.py name,dept,salary Lucia,sales,3100 John,it,4200 Adam,sales,2800 Jane,it,4200 <table><thead><tr><th>name</th><th>dept</th><th>salary</th></tr></thead><tbody><tr><td>Lucia</td><td>sales</td><td>3100</td></tr><tr><td>John</td><td>it</td><td>4200</td></tr><tr><td>Adam</td><td>sales</td><td>2800</td></tr><tr><td>Jane</td><td>it</td><td>4200</td></tr></tbody></table>
Loading data
The load method reads data into a dataset. It accepts a string, a
file, or bytes, and detects the format if none is given.
import tablib
with open('staff.csv', newline='') as f:
ds = tablib.Dataset().load(f)
print(ds.headers)
print(ds['salary'])
with open('staff.xlsx', 'rb') as f:
sheet = tablib.Dataset().load(f, format='xlsx')
print(sheet.title)
print(sheet['salary'])
data = tablib.Dataset().load('name;city\nTom;Oslo\nAnna;Rome\n',
format='csv', delimiter=';')
print(data.dict)
The first row of the CSV file becomes the headers. Values from CSV are always
strings, while the XLSX file keeps the numbers as integers and the sheet title.
Extra keyword arguments, here the semicolon delimiter, are passed
to the format reader.
$ python loading.py
['name', 'dept', 'salary']
['3100', '4200', '2800', '4200']
staff
[3100, 4200, 2800, 4200]
[{'name': 'Tom', 'city': 'Oslo'}, {'name': 'Anna', 'city': 'Rome'}]
Databooks
A Databook holds several datasets. Exported to XLSX, each dataset
becomes a sheet named after its title.
import tablib
staff = tablib.Dataset(
('Lucia', 'sales', 3100), ('John', 'it', 4200),
headers=['name', 'dept', 'salary'], title='staff')
depts = tablib.Dataset(
('sales', 'Bratislava'), ('it', 'Brno'),
headers=['dept', 'city'], title='departments')
book = tablib.Databook([staff, depts])
print(book.size)
with open('company.xlsx', 'wb') as f:
f.write(book.export('xlsx'))
with open('company.xlsx', 'rb') as f:
loaded = tablib.Databook().load(f.read(), 'xlsx')
for sheet in loaded.sheets():
print(sheet.title, sheet.headers, sheet.height)
We create a workbook with two sheets and load it back. The
sheets method returns the datasets of the loaded book with their
titles, headers, and row counts.
$ python databook.py 2 staff ['name', 'dept', 'salary'] 2 departments ['dept', 'city'] 2
Sales report
In the last example we load a CSV file of sales, remove duplicate rows, sum the sales by region, and export the report.
region,product,amount north,pens,120.50 south,pads,80.00 north,ink,45.25 east,pens,99.90 south,pads,80.00 east,clips,15.10 north,pens,60.00
The file contains one duplicate line: the second sale of pads in the south region.
import tablib
with open('sales.csv', newline='') as f:
sales = tablib.Dataset().load(f)
sales.remove_duplicates()
totals = {}
for region, product, amount in sales:
totals[region] = totals.get(region, 0) + float(amount)
report = tablib.Dataset(headers=['region', 'total', 'share'])
grand = sum(totals.values())
for region, total in sorted(totals.items()):
report.append([region, f'{total:.2f}', f'{total / grand:.1%}'])
report.append(['total', f'{grand:.2f}', '100.0%'])
print(len(sales), 'rows after removing duplicates')
print(report)
print(report.export('html'))
The remove_duplicates method removes identical rows in place.
Since CSV values are strings, the amounts are converted with
float before summing. The report is a new dataset, printed as a
text table and exported to HTML for a web page or an e-mail.
$ python report.py 6 rows after removing duplicates region|total |share ------|------|------ east |115.00|27.3% north |225.75|53.7% south |80.00 |19.0% total |420.75|100.0% <table><thead><tr><th>region</th><th>total</th><th>share</th></tr></thead><tbody><tr><td>east</td><td>115.00</td><td>27.3%</td></tr><tr><td>north</td><td>225.75</td><td>53.7%</td></tr><tr><td>south</td><td>80.00</td><td>19.0%</td></tr><tr><td>total</td><td>420.75</td><td>100.0%</td></tr></tbody></table>
Source
In this article we have created, modified, sorted, and filtered tabular datasets with tablib and imported and exported them in several formats. See also Python CSV, Python openpyxl, Python xlsxwriter, and PrettyTable tutorial.
Author
List all Python tutorials.