6
6
from pandas import Series , DataFrame , MultiIndex , Index
7
7
from pandas .core .groupby import Grouper
8
8
from pandas .core .reshape .util import cartesian_product
9
+ from pandas .core .index import _get_combined_index
9
10
from pandas .compat import range , lrange , zip
10
11
from pandas import compat
11
12
import pandas .core .common as com
@@ -493,6 +494,13 @@ def crosstab(index, columns, values=None, rownames=None, colnames=None,
493
494
rownames = _get_names (index , rownames , prefix = 'row' )
494
495
colnames = _get_names (columns , colnames , prefix = 'col' )
495
496
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
+
496
504
data = {}
497
505
data .update (zip (rownames , index ))
498
506
data .update (zip (colnames , columns ))
@@ -503,20 +511,21 @@ def crosstab(index, columns, values=None, rownames=None, colnames=None,
503
511
if values is not None and aggfunc is None :
504
512
raise ValueError ("values cannot be used without an aggfunc." )
505
513
514
+ df = DataFrame (data , index = common_idx )
506
515
if values is None :
507
- df = DataFrame (data )
508
516
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 }
514
518
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 )
520
529
521
530
# Post-process
522
531
if normalize is not False :
0 commit comments