diff --git a/AUTHORS b/AUTHORS index cd73e657..dd632cf0 100644 --- a/AUTHORS +++ b/AUTHORS @@ -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 diff --git a/docs/tutorial.rst b/docs/tutorial.rst index e4c2ae6f..6f451ce6 100644 --- a/docs/tutorial.rst +++ b/docs/tutorial.rst @@ -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')] + ----------------------- diff --git a/src/tablib/core.py b/src/tablib/core.py index b0b56fd2..de98a047 100644 --- a/src/tablib/core.py +++ b/src/tablib/core.py @@ -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