Skip to content

Commit 8b81dab

Browse files
committed
pivot_table strings as aggfunc
1 parent b5f1e71 commit 8b81dab

File tree

3 files changed

+19
-2
lines changed

3 files changed

+19
-2
lines changed

doc/source/whatsnew/v0.22.0.txt

+2-1
Original file line numberDiff line numberDiff line change
@@ -321,7 +321,8 @@ Reshaping
321321
- Bug in :func:`DataFrame.stack` which fails trying to sort mixed type levels under Python 3 (:issue:`18310`)
322322
- Fixed construction of a :class:`Series` from a ``dict`` containing ``NaN`` as key (:issue:`18480`)
323323
- Bug in :func:`Series.rank` where ``Series`` containing ``NaT`` modifies the ``Series`` inplace (:issue:`18521`)
324-
-
324+
- Bug in :func:`Dataframe.pivot_table` which fails when you pass a string for aggfunc arg (:issue:`18713`)
325+
-
325326

326327
Numeric
327328
^^^^^^^

pandas/core/reshape/pivot.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,9 @@ def pivot_table(data, values=None, index=None, columns=None, aggfunc='mean',
3838
fill_value=fill_value, aggfunc=func,
3939
margins=margins, margins_name=margins_name)
4040
pieces.append(table)
41-
keys.append(func.__name__)
41+
keys.append(getattr(func, '__name__', func))
42+
#keys.append(func.__name__)
43+
4244
return concat(pieces, keys=keys, axis=1)
4345

4446
keys = index + columns

pandas/tests/reshape/test_pivot.py

+14
Original file line numberDiff line numberDiff line change
@@ -1109,6 +1109,20 @@ def test_pivot_margins_name_unicode(self):
11091109
expected = pd.DataFrame(index=index)
11101110
tm.assert_frame_equal(table, expected)
11111111

1112+
def test_pivot_func_strings(self):
1113+
# GH #18713
1114+
f = lambda func: pivot_table(self.data, values=['D', 'E'],
1115+
index=['A', 'B'], columns='C',
1116+
aggfunc=func)
1117+
result = f('sum')
1118+
expected = f(np.sum)
1119+
tm.assert_frame_equal(result, expected)
1120+
result = f(['mean', 'std'])
1121+
means = f(np.mean)
1122+
stds = f(np.std)
1123+
expected = concat([means, stds], keys=['mean', 'std'], axis=1)
1124+
tm.assert_frame_equal(result, expected)
1125+
11121126

11131127
class TestCrosstab(object):
11141128

0 commit comments

Comments
 (0)