File tree Expand file tree Collapse file tree 2 files changed +41
-3
lines changed
Expand file tree Collapse file tree 2 files changed +41
-3
lines changed Original file line number Diff line number Diff line change @@ -1163,12 +1163,15 @@ def _normalize(
11631163
11641164 elif margins is True :
11651165 # keep index and column of pivoted table
1166- if table .empty :
1167- raise ValueError ("Can't get margins since the result dataframe is empty" )
11681166
11691167 table_index = table .index
11701168 table_columns = table .columns
1171- last_ind_or_col = table .iloc [- 1 , :].name
1169+ try :
1170+ last_ind_or_col = table .iloc [- 1 , :].name
1171+ except IndexError as err :
1172+ raise IndexError (
1173+ "Can't get margins since the result dataframe is empty"
1174+ ) from err
11721175
11731176 # check if margin name is not in (for MI cases) and not equal to last
11741177 # index/column and save the column and index margin
Original file line number Diff line number Diff line change @@ -877,3 +877,38 @@ def test_categoricals(a_dtype, b_dtype):
877877 expected = expected .loc [[0 , 2 , "All" ]]
878878 expected ["All" ] = expected ["All" ].astype ("int64" )
879879 tm .assert_frame_equal (result , expected )
880+
881+
882+ def test_crosstab_empty_result_with_normalize ():
883+ # https://github.com/pandas-dev/pandas/issues/60768
884+ index = ["index1" , "index2" , "index3" ]
885+ columns = ["col1" , "col2" , "col3" ]
886+ values = [1 , 2 , 3 ]
887+
888+ with pytest .raises (IndexError , match = "Can't get margins" ):
889+ # Raise error when margins=True
890+ crosstab (
891+ index ,
892+ columns ,
893+ values = values ,
894+ normalize = 1 ,
895+ margins = True ,
896+ dropna = True ,
897+ aggfunc = "skew" ,
898+ )
899+
900+ # No error when margins=False, just return empty DataFrame
901+ result = crosstab (
902+ index ,
903+ columns ,
904+ values = values ,
905+ normalize = 1 ,
906+ margins = False ,
907+ dropna = True ,
908+ aggfunc = "skew" ,
909+ )
910+ expected = DataFrame (
911+ index = Index ([], dtype = "str" , name = "row_0" ),
912+ columns = Index ([], dtype = "str" , name = "col_0" ),
913+ )
914+ tm .assert_frame_equal (result , expected )
You can’t perform that action at this time.
0 commit comments