Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions AUTHORS
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ Here is a list of past and present much-appreciated contributors:
Peyman Salehi
Rabin Nankhwa
Tak Hogan
Te-Shu Wang
Tommy Anthony
Tsuyoshi Hombashi
Tushar Makkar
Expand Down
16 changes: 16 additions & 0 deletions docs/tutorial.rst
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,22 @@ Let's find the average age. ::
>>> float(sum(ages)) / len(ages)
21.0

To create a new dataset containing selected rows and columns, use
:meth:`tablib.Dataset.subset`. Rows are selected by their zero-based position,
and columns are selected by their header values. ::

>>> import tablib
>>> people = tablib.Dataset(
... ('Ada', 'Lovelace', 36),
... ('Grace', 'Hopper', 85),
... headers=['First Name', 'Last Name', 'Age'],
... )
>>> selected = people.subset(rows=[1], cols=['Age', 'First Name'])
>>> selected.headers
['Age', 'First Name']
>>> list(selected)
[(85, 'Grace')]



-----------------------
Expand Down
27 changes: 25 additions & 2 deletions src/tablib/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -820,8 +820,31 @@ def wipe(self):
self.__headers = None

def subset(self, rows=None, cols=None):
"""Returns a new instance of the :class:`Dataset`,
including only specified rows and columns.
"""Returns a new :class:`Dataset` with selected rows and columns.

:param rows: (optional) iterable of zero-based row positions. If
omitted, all rows are selected in source order.
:param cols: (optional) iterable of column header values. If omitted,
all columns are selected in their existing header order.
:returns: a new :class:`Dataset` containing the selected data, or
``None`` if this dataset has no rows.

The :class:`Dataset` must have headers. Column selections use header
values, including when a header is numeric. The result preserves the
source row order and follows the order of ``cols``.

For example::

>>> people = tablib.Dataset(
... ('Ada', 'Lovelace', 36),
... ('Grace', 'Hopper', 85),
... headers=['First Name', 'Last Name', 'Age'],
... )
>>> selected = people.subset(rows=[1], cols=['Age', 'First Name'])
>>> selected.headers
['Age', 'First Name']
>>> list(selected)
[(85, 'Grace')]
"""

# Don't return if no data
Expand Down