66from pandas import Series , DataFrame , MultiIndex , Index
77from pandas .core .groupby import Grouper
88from pandas .core .reshape .util import cartesian_product
9+ from pandas .core .index import _get_combined_index
910from pandas .compat import range , lrange , zip
1011from pandas import compat
1112import pandas .core .common as com
@@ -493,6 +494,13 @@ def crosstab(index, columns, values=None, rownames=None, colnames=None,
493494 rownames = _get_names (index , rownames , prefix = 'row' )
494495 colnames = _get_names (columns , colnames , prefix = 'col' )
495496
497+ obs_idxes = [obj .index for objs in (index , columns ) for obj in objs
498+ if hasattr (obj , 'index' )]
499+ if obs_idxes :
500+ common_idx = _get_combined_index (obs_idxes , intersect = True )
501+ else :
502+ common_idx = None
503+
496504 data = {}
497505 data .update (zip (rownames , index ))
498506 data .update (zip (colnames , columns ))
@@ -503,20 +511,21 @@ def crosstab(index, columns, values=None, rownames=None, colnames=None,
503511 if values is not None and aggfunc is None :
504512 raise ValueError ("values cannot be used without an aggfunc." )
505513
514+ df = DataFrame (data , index = common_idx )
506515 if values is None :
507- df = DataFrame (data )
508516 df ['__dummy__' ] = 0
509- table = df .pivot_table ('__dummy__' , index = rownames , columns = colnames ,
510- aggfunc = len , margins = margins ,
511- margins_name = margins_name , dropna = dropna )
512- table = table .fillna (0 ).astype (np .int64 )
513-
517+ kwargs = {'aggfunc' : len , 'fill_value' : 0 }
514518 else :
515- data ['__dummy__' ] = values
516- df = DataFrame (data )
517- table = df .pivot_table ('__dummy__' , index = rownames , columns = colnames ,
518- aggfunc = aggfunc , margins = margins ,
519- margins_name = margins_name , dropna = dropna )
519+ df ['__dummy__' ] = values
520+ kwargs = {'aggfunc' : aggfunc }
521+
522+ table = df .pivot_table ('__dummy__' , index = rownames , columns = colnames ,
523+ margins = margins , margins_name = margins_name ,
524+ dropna = dropna , ** kwargs )
525+
526+ # GH 17013:
527+ if values is None and margins :
528+ table = table .fillna (0 ).astype (np .int64 )
520529
521530 # Post-process
522531 if normalize is not False :
0 commit comments