Repository: pandas-dev/pandas

Issue:
BUG: groupby.transform fails with incompatible size
#### Code Sample, a copy-pastable example if possible

``` python

np.random.seed(12345)
panel = pd.Panel(np.random.randn(125,200,10))
panel.iloc[:,:,0] = np.round(panel.iloc[:,:,0])
panel.iloc[:,:,1] = np.round(panel.iloc[:,:,1])
x = panel
cols = [0,1]
_x = x.swapaxes(0, 2).to_frame()
numeric_cols = []
for df_col in _x:
    if df_col not in cols and pd.core.common.is_numeric_dtype(_x[df_col].dtype):
        numeric_cols.append(df_col)

def _noop(df):
    return df

groups = _x.groupby(cols)
groups.transform(_noop)
```
#### Expected Output

The original input.  `_noop` is just a trivial example.
#### Error

``` python
C:\anaconda\lib\site-packages\pandas\core\internals.py in construction_error(tot_items, block_shape, axes, e)
   3968         raise ValueError("Empty data passed with indices specified.")
   3969     raise ValueError("Shape of passed values is {0}, indices imply {1}".format(
-> 3970         passed, implied))
   3971 
   3972 

ValueError: Shape of passed values is (8, 25000), indices imply (8, 25799)
```
#### Comments

The indices have reversed order, which is problem 1.  Also, one index has lost a value.
#### output of `pd.show_versions()`

```
INSTALLED VERSIONS
------------------
commit: None
python: 3.5.1.final.0
python-bits: 64
OS: Windows
OS-release: 10
machine: AMD64
processor: Intel64 Family 6 Model 94 Stepping 3, GenuineIntel
byteorder: little
LC_ALL: None
LANG: None

pandas: 0.18.1
nose: 1.3.7
pip: 8.1.2
setuptools: 23.0.0
Cython: 0.24
numpy: 1.11.0
scipy: 0.17.1
statsmodels: 0.8.0.dev0+f060948
xarray: 0.7.2
IPython: 4.2.0
sphinx: 1.3.1
patsy: 0.4.1
dateutil: 2.5.3
pytz: 2016.4
blosc: None
bottleneck: None
tables: 3.2.2
numexpr: 2.6.0
matplotlib: 1.5.1
openpyxl: None
xlrd: 1.0.0
xlwt: None
xlsxwriter: None
lxml: None
bs4: None
html5lib: None
httplib2: None
apiclient: None
sqlalchemy: None
pymysql: None
psycopg2: None
jinja2: 2.8
boto: None
pandas_datareader: 0.2.1
```



Discussion:
I have traced the bug to this line:

```
def _concat_indexes(indexes):
    return indexes[0].append(indexes[1:])
```

https://github.com/pydata/pandas/blob/883df65b095709e2146b1f36c9697b92eb913731/pandas/tools/merge.py#L1607

The bug is in the append operation on an index.

something in the concat is going wrong. you'll have to step thru and see.

Something is going wrong here:

https://github.com/pydata/pandas/blob/e8d9e79fc7d0a31e8c37c82f1e48d51cce59e9e0/pandas/indexes/multi.py#L1064

`get_level_values` seem to return the wrong thing.


Resolving patch:
diff --git a/pandas/indexes/range.py b/pandas/indexes/range.py
--- a/pandas/indexes/range.py
+++ b/pandas/indexes/range.py
@@ -58,15 +58,17 @@ def __new__(cls, start=None, stop=None, step=None, name=None, dtype=None,
 
         # validate the arguments
         def _ensure_int(value, field):
+            msg = ("RangeIndex(...) must be called with integers,"
+                   " {value} was passed for {field}")
+            if not is_scalar(value):
+                raise TypeError(msg.format(value=type(value).__name__,
+                                           field=field))
             try:
                 new_value = int(value)
                 assert(new_value == value)
-            except (ValueError, AssertionError):
-                raise TypeError("RangeIndex(...) must be called with integers,"
-                                " {value} was passed for {field}".format(
-                                    value=type(value).__name__,
-                                    field=field)
-                                )
+            except (TypeError, ValueError, AssertionError):
+                raise TypeError(msg.format(value=type(value).__name__,
+                                           field=field))
 
             return new_value
 


Test patch:
diff --git a/pandas/tests/indexes/test_range.py b/pandas/tests/indexes/test_range.py
--- a/pandas/tests/indexes/test_range.py
+++ b/pandas/tests/indexes/test_range.py
@@ -102,7 +102,8 @@ def test_constructor(self):
 
         # invalid args
         for i in [Index(['a', 'b']), Series(['a', 'b']), np.array(['a', 'b']),
-                  [], 'foo', datetime(2000, 1, 1, 0, 0), np.arange(0, 10)]:
+                  [], 'foo', datetime(2000, 1, 1, 0, 0), np.arange(0, 10),
+                  np.array([1]), [1]]:
             self.assertRaises(TypeError, lambda: RangeIndex(i))
 
     def test_constructor_same(self):
diff --git a/pandas/tools/tests/test_concat.py b/pandas/tools/tests/test_concat.py
--- a/pandas/tools/tests/test_concat.py
+++ b/pandas/tools/tests/test_concat.py
@@ -1444,6 +1444,20 @@ def test_default_index(self):
         tm.assert_frame_equal(res, exp, check_index_type=True,
                               check_column_type=True)
 
+    def test_concat_multiindex_rangeindex(self):
+        # GH13542
+        # when multi-index levels are RangeIndex objects
+        # there is a bug in concat with objects of len 1
+
+        df = DataFrame(np.random.randn(9, 2))
+        df.index = MultiIndex(levels=[pd.RangeIndex(3), pd.RangeIndex(3)],
+                              labels=[np.repeat(np.arange(3), 3),
+                                      np.tile(np.arange(3), 3)])
+
+        res = concat([df.iloc[[2, 3, 4], :], df.iloc[[5], :]])
+        exp = df.iloc[[2, 3, 4, 5], :]
+        tm.assert_frame_equal(res, exp)
+
 
 if __name__ == '__main__':
     nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'],