Repository: pandas-dev/pandas
Pull request:  Fix .transform crash when SeriesGroupBy is empty (#26208) 
- [X] closes #26208
- [x] tests added / passed
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry


Problem statement:
SeriesGroupBy.transform cannot handle empty series
#### Code Sample, a copy-pastable example if possible

```python
d = pd.DataFrame({1: [], 2: []})
g = d.groupby(1)
g[2].transform(lambda x: x)

Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "C:\python37\lib\site-packages\pandas\core\groupby\generic.py", line 945, in transform
    result = concat(results).sort_index()
  File "C:\python37\lib\site-packages\pandas\core\reshape\concat.py", line 228, in concat
    copy=copy, sort=sort)
  File "C:\python37\lib\site-packages\pandas\core\reshape\concat.py", line 262, in __init__
    raise ValueError('No objects to concatenate')
```

#### Problem description

Crashes on SeriesGroupby obj with zero length, which came from an empty dataframe. Would be nicer if pandas can handle this case without raising errors, by for example, just return an empty series. Thanks.

#### Expected Output

```
Series([], Name: 2, dtype: float64)
```

#### Output of ``pd.show_versions()``

<details>
INSTALLED VERSIONS
------------------
commit: None
python: 3.7.3.final.0
python-bits: 64
OS: Windows
OS-release: 10
machine: AMD64
processor: Intel64 Family 6 Model 142 Stepping 9, GenuineIntel
byteorder: little
LC_ALL: None
LANG: None
LOCALE: None.None
pandas: 0.24.2
pytest: 4.4.1
pip: 19.0.3
setuptools: 41.0.1
Cython: None
numpy: 1.15.4
scipy: 1.1.0
pyarrow: None
xarray: None
IPython: None
sphinx: None
patsy: 0.5.1
dateutil: 2.7.5
pytz: 2018.7
blosc: None
bottleneck: None
tables: None
numexpr: None
feather: None
matplotlib: 3.0.2
openpyxl: 2.5.12
xlrd: 1.2.0
xlwt: 1.3.0
xlsxwriter: None
lxml.etree: None
bs4: None
html5lib: None
sqlalchemy: None
pymysql: None
psycopg2: None
jinja2: None
s3fs: None
fastparquet: None
pandas_gbq: None
pandas_datareader: None
gcsfs: None

</details>

Hints from issue discussion:
I suppose that would make this consistent with apply and agg:

```python
>>> g[2].apply(lambda x: x)
Series([], Name: 2, dtype: float64)
>>> g[2].agg(lambda x: x)
Series([], Name: 2, dtype: float64)
```

If you want to take a look and have a simple way of making it work would take a PR
Related to #17093
Okay, thanks. I see a possible patch. Need to read over contribution guideline and set up a working env to create a PR.

Commit message: whats new for issue #26208

Patch to review:
diff --git a/doc/source/whatsnew/v0.25.0.rst b/doc/source/whatsnew/v0.25.0.rst
index 485a0a06fc247..56777f23698c7 100644
--- a/doc/source/whatsnew/v0.25.0.rst
+++ b/doc/source/whatsnew/v0.25.0.rst
@@ -391,6 +391,7 @@ Groupby/Resample/Rolling
 - Bug in :meth:`pandas.core.window.Rolling.min` and :meth:`pandas.core.window.Rolling.max` that caused a memory leak (:issue:`25893`)
 - Bug in :meth:`pandas.core.groupby.GroupBy.idxmax` and :meth:`pandas.core.groupby.GroupBy.idxmin` with datetime column would return incorrect dtype (:issue:`25444`, :issue:`15306`)
 - Bug in :meth:`pandas.core.groupby.GroupBy.cumsum`, :meth:`pandas.core.groupby.GroupBy.cumprod`, :meth:`pandas.core.groupby.GroupBy.cummin` and :meth:`pandas.core.groupby.GroupBy.cummax` with categorical column having absent categories, would return incorrect result or segfault (:issue:`16771`)
+- Bug in :meth:`pandas.core.groupby.SeriesGroupBy.transform` where transforming an empty SeriesGroupBy would raise error. Now returns empty Series, just like .apply and .agg. (:issue:`26208`)
 
 
 Reshaping
diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py
index f8b9ddce6000e..eeaa3f908893c 100644
--- a/pandas/core/groupby/generic.py
+++ b/pandas/core/groupby/generic.py
@@ -917,8 +917,11 @@ def transform(self, func, *args, **kwargs):
             s = klass(res, indexer)
             results.append(s)
 
-        from pandas.core.reshape.concat import concat
-        result = concat(results).sort_index()
+        if results:
+            from pandas.core.reshape.concat import concat
+            result = concat(results).sort_index()
+        else:
+            result = Series([])
 
         # we will only try to coerce the result type if
         # we have a numeric dtype, as these are *always* udfs
diff --git a/pandas/tests/groupby/test_transform.py b/pandas/tests/groupby/test_transform.py
index e330329644269..fb6fa0aecc7bb 100644
--- a/pandas/tests/groupby/test_transform.py
+++ b/pandas/tests/groupby/test_transform.py
@@ -880,3 +880,13 @@ def test_transform_absent_categories(func):
     result = getattr(df.y.groupby(df.x), func)()
     expected = df.y
     assert_series_equal(result, expected)
+
+
+def test_transform_empty_df():
+    # 26208
+    # handle empty SeriesGroupBy
+    d = pd.DataFrame({1: [], 2: []})
+    g = d.groupby(1)
+    result = g[2].transform(lambda x: x)
+    expected = pd.Series([], name=2)
+    assert_series_equal(result, expected)


Code review comments:
diff_hunk: @@ -880,3 +880,13 @@ def test_transform_absent_categories(func):
     result = getattr(df.y.groupby(df.x), func)()
     expected = df.y
     assert_series_equal(result, expected)
+
+
+def test_transform_empty_df():
path: pandas/tests/groupby/test_transform.py
text: @user1:
make the test name: test_evalute_with_empty_groups.

move to test_grouping

parameterize using .transform, .apply, and .agg (should be the same results) (you can pass in the function name, then use ``getattr`` inside)



@author:
Am having trouble implementing this, because I get an error on index mismatch when func is 'apply' or 'agg'.  Transform uses self._selected_obj.index, which is a RangeIndex, whereas apply/agg calls self._python_apply/agg_general, which returns a Series with Float64Index.

{AssertionError}Series.index are different

Series.index classes are not equivalent
[left]:  Float64Index([], dtype='float64', name=1)
[right]: RangeIndex(start=0, stop=0, step=1)


@author:
The various functions would create empty series with different index objects. This seems to be a bigger issue than what I am addressing. (Perhaps they all should use RangeIndex?) 

Given this, can I leave the test in test_transform.py?

@user1:
no, pls move the test as indicated