diff options
| author | Kenneth Reitz <me@kennethreitz.com> | 2010-11-11 10:59:08 -0500 |
|---|---|---|
| committer | Kenneth Reitz <me@kennethreitz.com> | 2010-11-11 10:59:08 -0500 |
| commit | b67762604f5ebe6130eb25610962c7918795c4dc (patch) | |
| tree | 8b0d39afcec67077b68063939812dbe54e7b1dae | |
| parent | 83a8346e8f7e3a267dfaab93951c13ac96c08528 (diff) | |
| parent | 657ab98d04d7d32b36eeae63c4da48e6b0a9c100 (diff) | |
| download | tablib-b67762604f5ebe6130eb25610962c7918795c4dc.tar.gz | |
Merge branch 'transpose' into develop
| -rw-r--r-- | tablib/core.py | 30 | ||||
| -rwxr-xr-x | test_tablib.py | 13 |
2 files changed, 42 insertions, 1 deletions
diff --git a/tablib/core.py b/tablib/core.py index 1417000..23026a2 100644 --- a/tablib/core.py +++ b/tablib/core.py @@ -507,7 +507,35 @@ class Dataset(object): _dset._data = [row for row in _dset._data if row.has_tag(tag)] return _dset - + + def transpose(self): + """Transpose a :class:`Dataset`, turning rows into columns and vice + versa, returning a new ``Dataset`` instance. The first row of the + original instance becomes the new header row.""" + + # Don't transpose if there is no data + if not self: + return + + _dset = Dataset() + # The first element of the headers stays in the headers, + # it is our "hinge" on which we rotate the data + new_headers = [self.headers[0]] + self[self.headers[0]] + + _dset.headers = new_headers + for column in self.headers: + + if column == self.headers[0]: + # It's in the headers, so skip it + continue + + # Adding the column name as now they're a regular column + row_data = [column] + self[column] + row_data = Row(row_data) + _dset.append(row=row_data) + + return _dset + def wipe(self): """Removes all content and headers from the :class:`Dataset` object.""" self._data = list() diff --git a/test_tablib.py b/test_tablib.py index 8687473..f203179 100755 --- a/test_tablib.py +++ b/test_tablib.py @@ -351,6 +351,19 @@ class TablibTestCase(unittest.TestCase): self.assertEqual(tablib.detect(_json)[0], tablib.formats.json) self.assertEqual(tablib.detect(_bunk)[0], None) + def test_transpose(self): + """Transpose a dataset.""" + + transposed_founders = self.founders.transpose() + first_row = transposed_founders[0] + second_row = transposed_founders[1] + + self.assertEqual(transposed_founders.headers, + ["first_name","John", "George", "Thomas"]) + self.assertEqual(first_row, + ("last_name","Adams", "Washington", "Jefferson")) + self.assertEqual(second_row, + ("gpa",90, 67, 50)) def test_wipe(self): """Purge a dataset.""" |
