Skip to content
Closed
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
13 changes: 13 additions & 0 deletions pandas/core/reshape.py
Original file line number Diff line number Diff line change
Expand Up @@ -336,6 +336,19 @@ def pivot(self, index=None, columns=None, values=None):
return indexed.unstack(columns)


def pivot_sparse(index, columns, values):
if (len(index) != len(columns)) or (len(columns) != len(values)):
raise AssertionError('Length of index, columns, and values must be the'
' same')

if len(index) == 0:
return SparseSeries(index=[])

hindex = MultiIndex.from_arrays([index, columns])
series = Series(values.values, index=hindex)
return series.to_sparse()


def pivot_simple(index, columns, values):
"""
Produce 'pivot' table based on 3 columns of this DataFrame.
Expand Down
15 changes: 14 additions & 1 deletion pandas/tests/test_reshape.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@

from pandas.util.testing import assert_frame_equal

from pandas.core.reshape import (melt, lreshape, get_dummies, wide_to_long)
from pandas.core.reshape import (melt, lreshape, get_dummies, wide_to_long, pivot_sparse)
import pandas.util.testing as tm
from pandas.compat import range, u

Expand Down Expand Up @@ -717,6 +717,19 @@ def test_stubs(self):
self.assertEqual(stubs, ['inc', 'edu'])


class TestSparePivot(tm.TestCase):

def setUp(self):
self.df = pd.DataFrame({'a': ['a', 'b', 'b', 'c'],\
'b': ['x', 'x', 'y', 'z'],\
'c': [1, 2, 3, 4]})

def test_simile_sparse_pivot(self):
result = pivot_sparse(self.df['a'], self.df['b'], self.df['c'])
actual_get = np.asarray(result.to_coo()[0].todense())
expected = self.df.pivot(index='a', columns='b', values='c').fillna(0).values.astype(self.df['c'].dtype)
self.assert_numpy_array_equal(actual_get, expected)

if __name__ == '__main__':
nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'],
exit=False)