Skip to content

Commit

Permalink
ENH: Panel.transpose #695
Browse files Browse the repository at this point in the history
  • Loading branch information
Chang She committed May 4, 2012
1 parent 976cab5 commit 47abe8c
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
17 changes: 17 additions & 0 deletions pandas/core/panel.py
Original file line number Diff line number Diff line change
Expand Up @@ -934,6 +934,23 @@ def swapaxes(self, axis1='major', axis2='minor'):

return self._constructor(new_values, *new_axes)

def transpose(self, items='items', major='major', minor='minor'):
"""
Permute the dimensions of the Panel
Returns
-------
y : Panel (new object)
"""
i, j, k = [self._get_axis_number(x) for x in [items, major, minor]]

if i == j or i == k or j == k:
raise ValueError('Must specify 3 unique axes')

new_axes = [self._get_axis(x) for x in [i, j, k]]
new_values = self.values.transpose((i, j, k)).copy()

This comment has been minimized.

Copy link
@wesm

wesm May 4, 2012

Member

Perhaps a copy keyword argument is in order with default copy=False (more ndarray-like, and sensitive to the fact that people work with very large panels)

This comment has been minimized.

Copy link
@changhiskhan

changhiskhan May 4, 2012

Contributor

yes, good point. i'll add it to swapaxes as well

return self._constructor(new_values, *new_axes)

def to_frame(self, filter_observations=True):
"""
Transform wide format into long (stacked) format as DataFrame
Expand Down
33 changes: 33 additions & 0 deletions pandas/tests/test_panel.py
Original file line number Diff line number Diff line change
Expand Up @@ -895,6 +895,39 @@ def test_swapaxes(self):
# this should also work
self.assertRaises(Exception, self.panel.swapaxes, 'items', 'items')

def test_transpose(self):
result = self.panel.transpose('minor', 'major', 'items')
expected = self.panel.swapaxes('items', 'minor')
assert_panel_equal(result, expected)

result = self.panel.transpose(2, 1, 0)
assert_panel_equal(result, expected)

result = self.panel.transpose('minor', 'items', 'major')
expected = self.panel.swapaxes('items', 'minor')
expected = expected.swapaxes('major', 'minor')
assert_panel_equal(result, expected)

result = self.panel.transpose(2, 0, 1)
assert_panel_equal(result, expected)

def test_transpose_sparse(self):
spanel = self.panel.to_sparse()
result = spanel.transpose('minor', 'major', 'items')
expected = spanel.swapaxes('items', 'minor')
assert_panel_equal(result, expected)

result = spanel.transpose(2, 1, 0)
assert_panel_equal(result, expected)

result = spanel.transpose('minor', 'items', 'major')
expected = spanel.swapaxes('items', 'minor')
expected = expected.swapaxes('major', 'minor')
assert_panel_equal(result, expected)

result = spanel.transpose(2, 0, 1)
assert_panel_equal(result, expected)

def test_to_frame(self):
# filtered
filtered = self.panel.to_frame()
Expand Down

0 comments on commit 47abe8c

Please sign in to comment.