diff --git a/src/tablib/core.py b/src/tablib/core.py index 252da78e..a7ebff2b 100644 --- a/src/tablib/core.py +++ b/src/tablib/core.py @@ -688,15 +688,11 @@ def sort(self, col, reverse=False): return _dset - def transpose(self): + def _transpose_with_headers(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 @@ -716,6 +712,35 @@ def transpose(self): _dset.append(row=row_data) return _dset + def _transpose_without_headers(self): + """Transpose a :class:`Dataset`, turning rows into columns and vice + versa, returning a new ``Dataset`` instance. This instance should not + have headers, or the dimension would be invalid.""" + + _dset = Dataset() + + # Add columns as rows in new instance + for index in range(0, len(self._data[0])): + row_data = self.get_col(index) + _dset.append(row=row_data) + + return _dset + + def transpose(self): + """Transpose a :class:`Dataset`, turning rows into columns and vice + versa, returning a new ``Dataset`` instance. If the instance has + headers, the first row of the original instance becomes the new header + row.""" + + # Don't transpose if there is no data + if not self: + return + + if self.headers is None: + return self._transpose_without_headers() + else: + return self._transpose_with_headers() + def stack(self, other): """Stack two :class:`Dataset` instances together by joining at the row level, and return new combined diff --git a/tests/test_tablib.py b/tests/test_tablib.py index 03ac58b2..9830d785 100755 --- a/tests/test_tablib.py +++ b/tests/test_tablib.py @@ -402,6 +402,21 @@ def test_transpose(self): self.assertEqual(second_row, ("gpa", 90, 67, 50)) + def test_transpose_empty_dataset(self): + data = tablib.Dataset() + self.assertEqual(data.transpose(), None) + + def test_transpose_with_no_headers(self): + data = tablib.Dataset() + data.append(('Cat', 'Eats fish', 26)) + data.append(['Dogs like', '_balls', 48]) + data.append([73, 'people', 'sleeps']) + dataTrans = data.transpose() + self.assertEqual(dataTrans[0], ('Cat', 'Dogs like', 73)) + self.assertEqual(dataTrans[1], ('Eats fish', '_balls', 'people')) + self.assertEqual(dataTrans[2], (26, 48, 'sleeps')) + self.assertEqual(data.transpose().transpose().dict, data.dict) + def test_transpose_multiple_headers(self): data = tablib.Dataset()