#NEWLINE# def test_crosstab_margins( self ) : #NEWLINE# #INDENT# a = np . random . randint ( 0 , 7 , size = 100 ) #NEWLINE# b = np . random . randint ( 0 , 3 , size = 100 ) #NEWLINE# c = np . random . randint ( 0 , 5 , size = 100 ) #NEWLINE# df = DataFrame ( { #NEWLINE# #INDENT# 'a' : a , #NEWLINE# 'b' : b , #NEWLINE# 'c' : c , #NEWLINE# #UNINDENT# } ) #NEWLINE# result = crosstab ( a , [ b , c ] , rownames = [ 'a' ] , colnames = ( 'b' , 'c' ) , margins = True ) #NEWLINE# self . assertEqual ( result . index . names , ( 'a' , ) ) #NEWLINE# self . assertEqual ( result . columns . names , [ 'b' , 'c' ] ) #NEWLINE# all_cols = result [ ( 'All' , '' ) ] #NEWLINE# exp_cols = df . groupby ( [ 'a' ] ) . size ( ) . astype ( 'i8' ) #NEWLINE# exp_cols = exp_cols . append ( Series ( [ len ( df ) ] , index = [ 'All' ] ) ) #NEWLINE# exp_cols . name = ( 'All' , '' ) #NEWLINE# tm . assert_series_equal ( all_cols , exp_cols ) #NEWLINE# all_rows = result . ix [ 'All' ] #NEWLINE# exp_rows = df . groupby ( [ 'b' , 'c' ] ) . size ( ) . astype ( 'i8' ) #NEWLINE# exp_rows = exp_rows . append ( Series ( [ len ( df ) ] , index = [ ( 'All' , '' ) ] ) ) #NEWLINE# exp_rows . name = 'All' #NEWLINE# exp_rows = exp_rows . reindex ( all_rows . index ) #NEWLINE# exp_rows = exp_rows . fillna ( 0 ) . astype ( np . int64 ) #NEWLINE# tm . assert_series_equal ( all_rows , exp_rows )