Repository: pandas-dev/pandas

Issue:
pd.Index([ ('b', 'c'), 'a']).drop(['a', ('b', 'c')]) raises ValueError
#### Code Sample, a copy-pastable example if possible

```bash
pietro@debiousci:~$ PYTHONHASHSEED=5 python3 -c "import pandas as pd; s1 = pd.Series([0,1], name='a'); s2 = pd.Series([2,3], name=('b', 'c')); print(pd.crosstab(s1, s2))"
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/home/pietro/nobackup/repo/pandas/pandas/core/reshape/pivot.py", line 466, in crosstab
    dropna=dropna, **kwargs)
  File "/home/pietro/nobackup/repo/pandas/pandas/core/frame.py", line 4462, in pivot_table
    margins_name=margins_name)
  File "/home/pietro/nobackup/repo/pandas/pandas/core/reshape/pivot.py", line 82, in pivot_table
    agged = grouped.agg(aggfunc)
  File "/home/pietro/nobackup/repo/pandas/pandas/core/groupby.py", line 4191, in aggregate
    return super(DataFrameGroupBy, self).aggregate(arg, *args, **kwargs)
  File "/home/pietro/nobackup/repo/pandas/pandas/core/groupby.py", line 3632, in aggregate
    return self._python_agg_general(arg, *args, **kwargs)
  File "/home/pietro/nobackup/repo/pandas/pandas/core/groupby.py", line 873, in _python_agg_general
    return self._wrap_aggregated_output(output)
  File "/home/pietro/nobackup/repo/pandas/pandas/core/groupby.py", line 4254, in _wrap_aggregated_output
    agg_labels = self._obj_with_exclusions._get_axis(agg_axis)
  File "pandas/_libs/properties.pyx", line 39, in pandas._libs.properties.cache_readonly.__get__ (pandas/_libs/properties.c:1604)
  File "/home/pietro/nobackup/repo/pandas/pandas/core/base.py", line 235, in _obj_with_exclusions
    return self.obj.drop(self.exclusions, axis=1)
  File "/home/pietro/nobackup/repo/pandas/pandas/core/generic.py", line 2517, in drop
    obj = obj._drop_axis(labels, axis, level=level, errors=errors)
  File "/home/pietro/nobackup/repo/pandas/pandas/core/generic.py", line 2549, in _drop_axis
    new_axis = axis.drop(labels, errors=errors)
  File "/home/pietro/nobackup/repo/pandas/pandas/core/indexes/base.py", line 3750, in drop
    labels = _index_labels_to_array(labels)
  File "/home/pietro/nobackup/repo/pandas/pandas/core/common.py", line 417, in _index_labels_to_array
    labels = _asarray_tuplesafe(labels)
  File "/home/pietro/nobackup/repo/pandas/pandas/core/common.py", line 386, in _asarray_tuplesafe
    result = np.asarray(values, dtype=dtype)
  File "/home/pietro/.local/lib/python3.5/site-packages/numpy/core/numeric.py", line 531, in asarray
    return array(a, dtype, copy=False, order=order)
ValueError: setting an array element with a sequence
```
Compare to:

```
pietro@debiousci:~$ PYTHONHASHSEED=6 python3 -c "import pandas as pd; s1 = pd.Series([0,1], name='a'); s2 = pd.Series([2,3], name=('b', 'c')); print(pd.crosstab(s1, s2))"
('b', 'c')  2  3
a               
0           1  0
1           0  1
```


#### Problem description

The above happens (pseudo-)randomly with python 3 and, it seems, always with python 2.

#### Expected Output

The case `` PYTHONHASHSEED=6``.

#### Output of ``pd.show_versions()``

<details>

In [2]: pd.show_versions()

INSTALLED VERSIONS
------------------
commit: None
python: 3.5.3.final.0
python-bits: 64
OS: Linux
OS-release: 4.9.0-3-amd64
machine: x86_64
processor: 
byteorder: little
LC_ALL: None
LANG: it_IT.UTF-8
LOCALE: it_IT.UTF-8

pandas: 0.22.0.dev0+131.g63e8527d3
pytest: 3.2.3
pip: 9.0.1
setuptools: 36.7.0
Cython: 0.25.2
numpy: 1.12.1
scipy: 0.19.0
pyarrow: None
xarray: None
IPython: 6.2.1
sphinx: 1.5.6
patsy: 0.4.1
dateutil: 2.6.1
pytz: 2017.2
blosc: None
bottleneck: 1.2.0dev
tables: 3.3.0
numexpr: 2.6.1
feather: 0.3.1
matplotlib: 2.0.0
openpyxl: None
xlrd: 1.0.0
xlwt: 1.1.2
xlsxwriter: 0.9.6
lxml: None
bs4: 4.5.3
html5lib: 0.999999999
sqlalchemy: 1.0.15
pymysql: None
psycopg2: None
jinja2: 2.10
s3fs: None
fastparquet: None
pandas_gbq: None
pandas_datareader: 0.2.1


</details>



Discussion:
> The above happens (pseudo-)randomly with python 3 and, it seems, always with python 2.

Sometimes it works also in Python 2.

Resolving patch:
diff --git a/pandas/core/common.py b/pandas/core/common.py
--- a/pandas/core/common.py
+++ b/pandas/core/common.py
@@ -398,7 +398,19 @@ def _asarray_tuplesafe(values, dtype=None):
     return result
 
 
-def _index_labels_to_array(labels):
+def _index_labels_to_array(labels, dtype=None):
+    """
+    Transform label or iterable of labels to array, for use in Index.
+
+    Parameters
+    ----------
+    dtype : dtype
+        If specified, use as dtype of the resulting array, otherwise infer.
+
+    Returns
+    -------
+    array
+    """
     if isinstance(labels, (compat.string_types, tuple)):
         labels = [labels]
 
@@ -408,7 +420,7 @@ def _index_labels_to_array(labels):
         except TypeError:  # non-iterable
             labels = [labels]
 
-    labels = _asarray_tuplesafe(labels)
+    labels = _asarray_tuplesafe(labels, dtype=dtype)
 
     return labels
 
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
@@ -3761,7 +3761,8 @@ def drop(self, labels, errors='raise'):
         -------
         dropped : Index
         """
-        labels = _index_labels_to_array(labels)
+        arr_dtype = 'object' if self.dtype == 'object' else None
+        labels = _index_labels_to_array(labels, dtype=arr_dtype)
         indexer = self.get_indexer(labels)
         mask = indexer == -1
         if mask.any():


Test patch:
diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py
--- a/pandas/tests/indexes/test_base.py
+++ b/pandas/tests/indexes/test_base.py
@@ -1429,6 +1429,27 @@ def test_drop(self):
         expected = Index([1, 2])
         tm.assert_index_equal(dropped, expected)
 
+    @pytest.mark.parametrize("values", [['a', 'b', ('c', 'd')],
+                                        ['a', ('c', 'd'), 'b'],
+                                        [('c', 'd'), 'a', 'b']])
+    @pytest.mark.parametrize("to_drop", [[('c', 'd'), 'a'], ['a', ('c', 'd')]])
+    def test_drop_tuple(self, values, to_drop):
+        # GH 18304
+        index = pd.Index(values)
+        expected = pd.Index(['b'])
+
+        result = index.drop(to_drop)
+        tm.assert_index_equal(result, expected)
+
+        removed = index.drop(to_drop[0])
+        for drop_me in to_drop[1], [to_drop[1]]:
+            result = removed.drop(drop_me)
+            tm.assert_index_equal(result, expected)
+
+        removed = index.drop(to_drop[1])
+        for drop_me in to_drop[1], [to_drop[1]]:
+            pytest.raises(ValueError, removed.drop, drop_me)
+
     def test_tuple_union_bug(self):
         import pandas
         import numpy as np
diff --git a/pandas/tests/reshape/test_pivot.py b/pandas/tests/reshape/test_pivot.py
--- a/pandas/tests/reshape/test_pivot.py
+++ b/pandas/tests/reshape/test_pivot.py
@@ -1631,3 +1631,15 @@ def test_crosstab_dup_index_names(self):
                                 index=expected_index,
                                 columns=expected_index)
         tm.assert_frame_equal(result, expected)
+
+    @pytest.mark.parametrize("names", [['a', ('b', 'c')],
+                                       [('a', 'b'), 'c']])
+    def test_crosstab_tuple_name(self, names):
+        s1 = pd.Series(range(3), name=names[0])
+        s2 = pd.Series(range(1, 4), name=names[1])
+
+        mi = pd.MultiIndex.from_arrays([range(3), range(1, 4)], names=names)
+        expected = pd.Series(1, index=mi).unstack(1, fill_value=0)
+
+        result = pd.crosstab(s1, s2)
+        tm.assert_frame_equal(result, expected)