Skip to content

Commit 5aa5b80

Browse files
committed
ENH: pass multiple values columns to pivot_table, GH #381
1 parent d9fdd00 commit 5aa5b80

File tree

2 files changed

+23
-3
lines changed

2 files changed

+23
-3
lines changed

pandas/tools/pivot.py

+14-2
Original file line numberDiff line numberDiff line change
@@ -51,10 +51,22 @@ def pivot_table(data, values=None, rows=None, cols=None, aggfunc=np.mean,
5151
cols = _convert_by(cols)
5252

5353
keys = rows + cols
54+
55+
values_passed = values is not None
56+
if values_passed:
57+
if isinstance(values, (list, tuple)):
58+
values_multi = True
59+
else:
60+
values_multi = False
61+
values = [values]
62+
63+
if values_passed:
64+
data = data[keys + values]
65+
5466
grouped = data.groupby(keys)
5567

56-
if values is not None:
57-
grouped = grouped[values]
68+
if values_passed and not values_multi:
69+
grouped = grouped[values[0]]
5870

5971
agged = grouped.agg(aggfunc)
6072

pandas/tools/tests/test_pivot.py

+9-1
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,8 @@ def setUp(self):
1919
'dull', 'shiny', 'shiny', 'dull',
2020
'shiny', 'shiny', 'shiny'],
2121
'D' : np.random.randn(11),
22-
'E' : np.random.randn(11)})
22+
'E' : np.random.randn(11),
23+
'F' : np.random.randn(11)})
2324

2425
def test_pivot_table(self):
2526
rows = ['A', 'B']
@@ -46,6 +47,13 @@ def test_pivot_table_multiple(self):
4647
expected = self.data.groupby(rows + [cols]).agg(np.mean).unstack()
4748
assert_frame_equal(table, expected)
4849

50+
def test_pivot_multi_values(self):
51+
result = pivot_table(self.data, values=['D', 'E'],
52+
rows='A', cols=['B', 'C'])
53+
expected = pivot_table(self.data.drop(['F'], axis=1),
54+
rows='A', cols=['B', 'C'])
55+
assert_frame_equal(result, expected)
56+
4957
if __name__ == '__main__':
5058
import nose
5159
nose.runmodule(argv=[__file__,'-vvs','-x','--pdb', '--pdb-failure'],

0 commit comments

Comments
 (0)