@@ -2972,6 +2972,37 @@ def f(x):
2972
2972
result = g .apply (f )
2973
2973
assert_frame_equal (result , expected )
2974
2974
2975
+ def test_apply_preserves_multiindex_columns (self ):
2976
+ # GH 16231
2977
+ # the original failing case
2978
+ cols = pd .MultiIndex .from_tuples ([('A' , 'a' , '' , 'one' ),
2979
+ ('B' , 'b' , 'i' , 'two' )])
2980
+ ind = pd .DatetimeIndex (start = '2017-01-01' , freq = '15Min' , periods = 8 )
2981
+ df = pd .DataFrame (np .random .randn (8 ,2 ), index = ind , columns = cols )
2982
+
2983
+ agg_dict = {col : (np .sum if col [3 ] == 'one' else np .mean )
2984
+ for col in df .columns }
2985
+ resampled = df .resample ('H' ).apply (lambda x : agg_dict [x .name ](x ))
2986
+ assert isinstance (resampled .columns , pd .MultiIndex )
2987
+
2988
+ @pytest .mark .parametrize ('nlevel' , range (1 , 6 ))
2989
+ @pytest .mark .parametrize ('ncol' , [1 , 2 ])
2990
+ @pytest .mark .parametrize ('freq' , ['D' , '360Min' ])
2991
+ def test_apply_preserves_multiindex_columns_grid (self , nlevel , ncol , freq ):
2992
+ # GH 16231
2993
+ cols = pd .MultiIndex .from_tuples ([[i ] * nlevel for i in range (ncol )],
2994
+ names = ['lev_{}' .format (lev )
2995
+ for lev in range (nlevel )])
2996
+ idx = pd .date_range ('2000-01-01' , freq = "H" , periods = 50 )
2997
+ df = pd .DataFrame (np .random .randn (len (idx ), len (cols )),
2998
+ columns = cols , index = idx )
2999
+
3000
+ resampled = df .resample (freq )
3001
+
3002
+ via_direct = resampled .sum ()
3003
+ via_apply = resampled .apply (lambda x : x .sum ())
3004
+ tm .assert_frame_equal (via_direct , via_apply )
3005
+
2975
3006
def test_resample_groupby_with_label (self ):
2976
3007
# GH 13235
2977
3008
index = date_range ('2000-01-01' , freq = '2D' , periods = 5 )
0 commit comments