Repository: pandas-dev/pandas

Issue:
Index.putmask with an invalid mask causes a crash due to stack overflow
#### Code Sample, a copy-pastable example if possible
Seems to happen regardless of the type of index, and for any type of invalid mask.

`mask` with too few elements:
```python
In [2]: idx = pd.Index(list('abca'))

In [3]: idx.putmask([True, True, False], 'x')
Fatal Python error: Cannot recover from stack overflow.
```

`mask` with too many elements:
```python
In [2]: idx = pd.CategoricalIndex(list('abca'))

In [3]: idx.putmask(np.array([True, False]*3), 'c')
Fatal Python error: Cannot recover from stack overflow.
```

Entirely wrong `mask`:

```python
In [2]: idx = pd.period_range('2017Q1', periods=4, freq='Q')

In [3]: idx.putmask('foo', 'bar')
Fatal Python error: Cannot recover from stack overflow.
```

Doesn't appear to be an issue with `np.putmask`:
```python
In [2]: a = np.arange(5)

In [3]: np.putmask(a, [True, False], -1)
---------------------------------------------------------------------------
ValueError: putmask: mask and data must be the same size
```

#### Problem description
An invalid mask in `Index.putmask` causes a stack overflow.

#### Expected Output
I'd expect an exception to be raised.

#### Output of ``pd.show_versions()``

<details>

INSTALLED VERSIONS
------------------
commit: b00e62c273cd60739b538314156b65f0f79350f9
python: 3.6.1.final.0
python-bits: 64
OS: Windows
OS-release: 10
machine: AMD64
processor: Intel64 Family 6 Model 78 Stepping 3, GenuineIntel
byteorder: little
LC_ALL: None
LANG: None
LOCALE: None.None

pandas: 0.22.0.dev0+159.gb00e62c
pytest: 3.1.2
pip: 9.0.1
setuptools: 27.2.0
Cython: 0.25.2
numpy: 1.13.1
scipy: 0.19.1
pyarrow: 0.6.0
xarray: 0.9.6
IPython: 6.1.0
sphinx: 1.5.6
patsy: 0.4.1
dateutil: 2.6.0
pytz: 2017.2
blosc: None
bottleneck: None
tables: 3.4.2
numexpr: 2.6.2
feather: 0.4.0
matplotlib: 2.0.2
openpyxl: 2.4.8
xlrd: 1.1.0
xlwt: 1.3.0
xlsxwriter: 0.9.8
lxml: 3.8.0
bs4: None
html5lib: 0.999
sqlalchemy: 1.1.13
pymysql: None
psycopg2: None
jinja2: 2.9.6
s3fs: None
fastparquet: 0.1.0
pandas_gbq: None
pandas_datareader: None

</details>



Discussion:
this almost a directly pass thru to ``np.putmask``, I think we maybe recursing via the conversion to object. PR welcome!

Resolving patch:
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -1939,7 +1939,10 @@ def putmask(self, mask, value):
         try:
             np.putmask(values, mask, self._convert_for_op(value))
             return self._shallow_copy(values)
-        except (ValueError, TypeError):
+        except (ValueError, TypeError) as err:
+            if is_object_dtype(self):
+                raise err
+
             # coerces to object
             return self.astype(object).putmask(mask, value)
 


Test patch:
diff --git a/pandas/tests/indexes/common.py b/pandas/tests/indexes/common.py
--- a/pandas/tests/indexes/common.py
+++ b/pandas/tests/indexes/common.py
@@ -1032,3 +1032,16 @@ def test_map(self):
 
         dict_map = {}
         tm.assert_index_equal(index.map(dict_map), nan_index)
+
+    def test_putmask_with_wrong_mask(self):
+        # GH18368
+        index = self.create_index()
+
+        with pytest.raises(ValueError):
+            index.putmask(np.ones(len(index) + 1, np.bool), 1)
+
+        with pytest.raises(ValueError):
+            index.putmask(np.ones(len(index) - 1, np.bool), 1)
+
+        with pytest.raises(ValueError):
+            index.putmask('foo', 1)