@@ -1109,18 +1109,46 @@ def test_pivot_margins_name_unicode(self):
1109
1109
expected = pd .DataFrame (index = index )
1110
1110
tm .assert_frame_equal (table , expected )
1111
1111
1112
- def test_pivot_func_strings (self ):
1112
+ def test_pivot_string_as_func (self ):
1113
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 )
1114
+ data = DataFrame ({'A' : ['foo' , 'foo' , 'foo' , 'foo' , 'bar' , 'bar' ,
1115
+ 'bar' , 'bar' , 'foo' , 'foo' , 'foo' ],
1116
+ 'B' : ['one' , 'one' , 'one' , 'two' , 'one' , 'one' ,
1117
+ 'one' , 'two' , 'two' , 'two' , 'one' ],
1118
+ 'C' : range (11 )})
1119
+
1120
+ result = pivot_table (data , index = 'A' , columns = 'B' , aggfunc = 'sum' )
1121
+ mi = MultiIndex (levels = [['C' ], ['one' , 'two' ]],
1122
+ labels = [[0 , 0 ], [0 , 1 ]], names = [None , 'B' ])
1123
+ expected = DataFrame ({('C' , 'one' ): {'bar' : 15 , 'foo' : 13 },
1124
+ ('C' , 'two' ): {'bar' : 7 , 'foo' : 20 }},
1125
+ columns = mi ).rename_axis ('A' )
1119
1126
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 )
1127
+
1128
+ result = pivot_table (data , index = 'A' , columns = 'B' ,
1129
+ aggfunc = ['sum' , 'mean' ])
1130
+ mi = MultiIndex (levels = [['sum' , 'mean' ], ['C' ], ['one' , 'two' ]],
1131
+ labels = [[0 , 0 , 1 , 1 ], [0 , 0 , 0 , 0 ], [0 , 1 , 0 , 1 ]],
1132
+ names = [None , None , 'B' ])
1133
+ expected = DataFrame ({('mean' , 'C' , 'one' ): {'bar' : 5.0 , 'foo' : 3.25 },
1134
+ ('mean' , 'C' , 'two' ): {'bar' : 7.0 ,
1135
+ 'foo' : 6.666666666666667 },
1136
+ ('sum' , 'C' , 'one' ): {'bar' : 15 , 'foo' : 13 },
1137
+ ('sum' , 'C' , 'two' ): {'bar' : 7 , 'foo' : 20 }},
1138
+ columns = mi ).rename_axis ('A' )
1139
+ tm .assert_frame_equal (result , expected )
1140
+
1141
+ funcs = [('sum' , np .sum ), ('mean' , np .mean ), ('std' , np .std ),
1142
+ (['sum' , 'mean' ], [np .sum , np .mean ]),
1143
+ (['sum' , 'std' ], [np .sum , np .std ]),
1144
+ (['std' , 'mean' ], [np .std , np .mean ])]
1145
+
1146
+ @pytest .mark .parametrize ("f, f_numpy" , funcs )
1147
+ def test_pivot_string_func_vs_func (self , f , f_numpy ):
1148
+ # GH #18713
1149
+ result = pivot_table (self .data , index = 'A' , columns = 'B' , aggfunc = f )
1150
+ expected = pivot_table (self .data , index = 'A' , columns = 'B' ,
1151
+ aggfunc = f_numpy )
1124
1152
tm .assert_frame_equal (result , expected )
1125
1153
1126
1154
0 commit comments