Repository: modin-project/modin

Issue:
groupby('column')['column'].count() throws an exception
### System information
- **OS Platform and Distribution (e.g., Linux Ubuntu 16.04)**:

Ubuntu 20.04

- **Modin version** (`modin.__version__`):

0.7.3+59.g2f10057

- **Python version**:

Python 3.8.2

- **Code we can use to reproduce**:

```python
import modin.pandas as pd

df = pd.DataFrame([[1, 2], [4, 5], [7, 8]],
                  index=[1, 2, 3],
                  columns=['max_speed', 'shield'])
print(df)

df1 = df.groupby('max_speed')['max_speed'].count()
print(df1)
```

<!--
You can obtain the Modin version with

python -c "import modin; print(modin.__version__)"
-->

### Describe the problem
<!-- Describe the problem clearly here. -->

When ran on Modin, this script throws an exception
```
Traceback (most recent call last):
  File "groupby_test.py", line 8, in <module>
    df1 = df.groupby('max_speed')['max_speed'].count()
  File "/localdisk/gashiman/modin/modin/pandas/groupby.py", line 452, in count
    return self._groupby_reduce(
  File "/localdisk/gashiman/modin/modin/pandas/groupby.py", line 519, in _groupby_reduce
    query_compiler=groupby_qc.groupby_reduce(
  File "/localdisk/gashiman/modin/modin/backends/pandas/query_compiler.py", line 1169, in groupby_reduce
    first_column = qc.columns[0]
  File "/nfs/site/home/gashiman/.local/lib/python3.8/site-packages/pandas/core/indexes/base.py", line 3929, in __getitem__
    return getitem(key)
IndexError: index 0 is out of bounds for axis 0 with size 0
```

### Source code / logs
<!-- Include any logs or source code that would be helpful to diagnose the problem. If including tracebacks, please include the full traceback. Large logs and files should be attached. Try to provide a reproducible test case that is the bare minimum necessary to generate the problem. -->

groupby('column')['column'].count() throws an exception
### System information
- **OS Platform and Distribution (e.g., Linux Ubuntu 16.04)**:

Ubuntu 20.04

- **Modin version** (`modin.__version__`):

0.7.3+59.g2f10057

- **Python version**:

Python 3.8.2

- **Code we can use to reproduce**:

```python
import modin.pandas as pd

df = pd.DataFrame([[1, 2], [4, 5], [7, 8]],
                  index=[1, 2, 3],
                  columns=['max_speed', 'shield'])
print(df)

df1 = df.groupby('max_speed')['max_speed'].count()
print(df1)
```

<!--
You can obtain the Modin version with

python -c "import modin; print(modin.__version__)"
-->

### Describe the problem
<!-- Describe the problem clearly here. -->

When ran on Modin, this script throws an exception
```
Traceback (most recent call last):
  File "groupby_test.py", line 8, in <module>
    df1 = df.groupby('max_speed')['max_speed'].count()
  File "/localdisk/gashiman/modin/modin/pandas/groupby.py", line 452, in count
    return self._groupby_reduce(
  File "/localdisk/gashiman/modin/modin/pandas/groupby.py", line 519, in _groupby_reduce
    query_compiler=groupby_qc.groupby_reduce(
  File "/localdisk/gashiman/modin/modin/backends/pandas/query_compiler.py", line 1169, in groupby_reduce
    first_column = qc.columns[0]
  File "/nfs/site/home/gashiman/.local/lib/python3.8/site-packages/pandas/core/indexes/base.py", line 3929, in __getitem__
    return getitem(key)
IndexError: index 0 is out of bounds for axis 0 with size 0
```

### Source code / logs
<!-- Include any logs or source code that would be helpful to diagnose the problem. If including tracebacks, please include the full traceback. Large logs and files should be attached. Try to provide a reproducible test case that is the bare minimum necessary to generate the problem. -->



Discussion:

Resolving patch:
diff --git a/modin/pandas/groupby.py b/modin/pandas/groupby.py
--- a/modin/pandas/groupby.py
+++ b/modin/pandas/groupby.py
@@ -266,15 +266,20 @@ def backfill(self, limit=None):
 
     def __getitem__(self, key):
         kwargs = self._kwargs.copy()
+        # Most of time indexing DataFrameGroupBy results in another DataFrameGroupBy object unless circumstances are
+        # special in which case SeriesGroupBy has to be returned. Such circumstances are when key equals to a single
+        # column name and is not a list of column names or list of one column name.
+        make_dataframe = True
         if self._drop:
             if not isinstance(key, list):
                 key = [key]
                 kwargs["squeeze"] = True
+                make_dataframe = False
         # When `as_index` is False, pandas will always convert to a `DataFrame`, we
         # convert to a list here so that the result will be a `DataFrame`.
         elif not self._as_index and not isinstance(key, list):
             key = [key]
-        if isinstance(key, list):
+        if isinstance(key, list) and (make_dataframe or not self._as_index):
             return DataFrameGroupBy(
                 self._df[key],
                 self._by,


Test patch:
diff --git a/modin/pandas/test/test_groupby.py b/modin/pandas/test/test_groupby.py
--- a/modin/pandas/test/test_groupby.py
+++ b/modin/pandas/test/test_groupby.py
@@ -23,7 +23,9 @@
 
 def modin_df_almost_equals_pandas(modin_df, pandas_df):
     difference = to_pandas(modin_df) - pandas_df
-    diff_max = difference.max().max()
+    diff_max = difference.max()
+    if isinstance(diff_max, pandas.Series):
+        diff_max = diff_max.max()
     assert (
         to_pandas(modin_df).equals(pandas_df)
         or diff_max < 0.0001
@@ -452,20 +454,41 @@ def test_simple_col_groupby():
 @pytest.mark.parametrize(
     "by", [np.random.randint(0, 100, size=2 ** 8), lambda x: x % 3, None]
 )
-@pytest.mark.parametrize("as_index", [True, False])
-def test_series_groupby(by, as_index):
-    series_data = np.random.randint(97, 198, size=2 ** 8)
-    modin_series = pd.Series(series_data)
-    pandas_series = pandas.Series(series_data)
+@pytest.mark.parametrize("as_index_series_or_dataframe", [0, 1, 2])
+def test_series_groupby(by, as_index_series_or_dataframe):
+    if as_index_series_or_dataframe <= 1:
+        as_index = as_index_series_or_dataframe == 1
+        series_data = np.random.randint(97, 198, size=2 ** 8)
+        modin_series = pd.Series(series_data)
+        pandas_series = pandas.Series(series_data)
+    else:
+        as_index = True
+        pandas_series = pandas.DataFrame(
+            {
+                "col1": [0, 1, 2, 3],
+                "col2": [4, 5, 6, 7],
+                "col3": [3, 8, 12, 10],
+                "col4": [17, 13, 16, 15],
+                "col5": [-4, -5, -6, -7],
+            }
+        )
+        modin_series = from_pandas(pandas_series)
+        if isinstance(by, np.ndarray) or by is None:
+            by = np.random.randint(0, 100, size=len(pandas_series.index))
+
     n = 1
 
     try:
         pandas_groupby = pandas_series.groupby(by, as_index=as_index)
+        if as_index_series_or_dataframe == 2:
+            pandas_groupby = pandas_groupby["col1"]
     except Exception as e:
         with pytest.raises(type(e)):
             modin_series.groupby(by, as_index=as_index)
     else:
         modin_groupby = modin_series.groupby(by, as_index=as_index)
+        if as_index_series_or_dataframe == 2:
+            modin_groupby = modin_groupby["col1"]
 
         modin_groupby_equals_pandas(modin_groupby, pandas_groupby)
         eval_ngroups(modin_groupby, pandas_groupby)
@@ -771,12 +794,15 @@ def eval_take(modin_groupby, pandas_groupby):
 
 def eval___getattr__(modin_groupby, pandas_groupby, item):
     try:
-        pandas_result = pandas_groupby[item].count()
+        pandas_groupby = pandas_groupby[item]
+        pandas_result = pandas_groupby.count()
     except Exception as e:
         with pytest.raises(type(e)):
             modin_groupby[item].count()
     else:
-        df_equals(modin_groupby[item].count(), pandas_result)
+        modin_groupby = modin_groupby[item]
+        modin_result = modin_groupby.count()
+        df_equals(modin_result, pandas_result)
 
 
 def eval_groups(modin_groupby, pandas_groupby):