@@ -1754,11 +1754,16 @@ def _iterate_column_groupbys(self):
1754
1754
def _apply_to_column_groupbys (self , func ) -> DataFrame :
1755
1755
from pandas .core .reshape .concat import concat
1756
1756
1757
- return concat (
1758
- (func (col_groupby ) for _ , col_groupby in self ._iterate_column_groupbys ()),
1759
- keys = self ._selected_obj .columns ,
1760
- axis = 1 ,
1761
- )
1757
+ columns = self ._selected_obj .columns
1758
+ results = [
1759
+ func (col_groupby ) for _ , col_groupby in self ._iterate_column_groupbys ()
1760
+ ]
1761
+
1762
+ if not len (results ):
1763
+ # concat would raise
1764
+ return DataFrame ([], columns = columns , index = self .grouper .result_index )
1765
+ else :
1766
+ return concat (results , keys = columns , axis = 1 )
1762
1767
1763
1768
def count (self ) -> DataFrame :
1764
1769
"""
@@ -1850,27 +1855,30 @@ def nunique(self, dropna: bool = True) -> DataFrame:
1850
1855
# Try to consolidate with normal wrapping functions
1851
1856
1852
1857
obj = self ._obj_with_exclusions
1853
- axis_number = obj ._get_axis_number (self .axis )
1854
- other_axis = int (not axis_number )
1855
- if axis_number == 0 :
1858
+ if self .axis == 0 :
1856
1859
iter_func = obj .items
1857
1860
else :
1858
1861
iter_func = obj .iterrows
1859
1862
1860
- results = concat (
1861
- [
1862
- SeriesGroupBy (content , selection = label , grouper = self .grouper ).nunique (
1863
- dropna
1864
- )
1865
- for label , content in iter_func ()
1866
- ],
1867
- axis = 1 ,
1868
- )
1869
- results = cast (DataFrame , results )
1863
+ res_list = [
1864
+ SeriesGroupBy (content , selection = label , grouper = self .grouper ).nunique (
1865
+ dropna
1866
+ )
1867
+ for label , content in iter_func ()
1868
+ ]
1869
+ if res_list :
1870
+ results = concat (res_list , axis = 1 )
1871
+ results = cast (DataFrame , results )
1872
+ else :
1873
+ # concat would raise
1874
+ results = DataFrame (
1875
+ [], index = self .grouper .result_index , columns = obj .columns [:0 ]
1876
+ )
1870
1877
1871
- if axis_number == 1 :
1878
+ if self . axis == 1 :
1872
1879
results = results .T
1873
1880
1881
+ other_axis = 1 - self .axis
1874
1882
results ._get_axis (other_axis ).names = obj ._get_axis (other_axis ).names
1875
1883
1876
1884
if not self .as_index :
0 commit comments