Repository: pandas-dev/pandas
Pull request: ERR: Raise a better error for numpy singletons in Index
- [x] closes #33017
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`


Problem statement:
Unspecific error message when setting singular index with np dtype
#### Code Sample, a copy-pastable example if possible

```python
some_np_array = np.array([43, 56])

# unspecific error message 'TypeError: len() of unsized object':
pd.DataFrame([4324, 345], index=some_np_array[0])
pd.Series([4324, 345], index=some_np_array[0])

# specific error message 'TypeError: Index(...) must be called with a collection of some kind, 5 was passed':
pd.DataFrame([4324, 345], index=5)
pd.Series([4324, 345], index=5)
```
#### Problem description

When passing a non-collection type as an index, pandas typically raises a quite helpful error message of the following form:
`TypeError: Index(...) must be called with a collection of some kind, 5 was passed`

Whereas when passing a non-standard type non-collection item as an index, pandas seems to raise some unspecific and misleading error:
`TypeError: len() of unsized object`

#### Expected Output
Specific error message, even when using np.float64, np.int64 etc. as type of singular values.

#### Output of ``pd.show_versions()``

<details>

INSTALLED VERSIONS
------------------
commit           : None
python           : 3.7.7.final.0
python-bits      : 64
OS               : Windows
OS-release       : 7
machine          : AMD64
processor        : Intel64 Family 6 Model 58 Stepping 9, GenuineIntel
byteorder        : little
LC_ALL           : None
LANG             : en
LOCALE           : None.None

pandas           : 1.0.3
numpy            : 1.18.1
pytz             : 2019.3
dateutil         : 2.8.1
pip              : 20.0.2
setuptools       : 46.1.1.post20200323
Cython           : 0.29.15
pytest           : 5.4.1
hypothesis       : 5.5.4
sphinx           : 2.4.0
blosc            : None
feather          : None
xlsxwriter       : 1.2.8
lxml.etree       : 4.5.0
html5lib         : 1.0.1
pymysql          : None
psycopg2         : None
jinja2           : 2.11.1
IPython          : 7.13.0
pandas_datareader: None
bs4              : 4.8.2
bottleneck       : 1.3.2
fastparquet      : None
gcsfs            : None
lxml.etree       : 4.5.0
matplotlib       : 3.1.3
numexpr          : 2.7.1
odfpy            : None
openpyxl         : 3.0.3
pandas_gbq       : None
pyarrow          : None
pytables         : None
pytest           : 5.4.1
pyxlsb           : None
s3fs             : None
scipy            : 1.4.1
sqlalchemy       : 1.3.15
tables           : 3.6.1
tabulate         : None
xarray           : None
xlrd             : 1.2.0
xlwt             : 1.3.0
xlsxwriter       : 1.2.8
numba            : 0.48.0

</details>

Hints from issue discussion:
I suppose it could raise a better error message (which likely shouldn't change if the value happens to come from inside a numpy array). The behavior now is because even the singleton `np.array([1, 2])[0]` has an `__array__` attribute so the scalar check gets skipped: https://github.com/pandas-dev/pandas/blob/master/pandas/core/indexes/base.py#L398

Commit message: Add note

Patch to review:
diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst
index dcbfe6aeb9a12..3993f8ffa5d14 100644
--- a/doc/source/whatsnew/v1.1.0.rst
+++ b/doc/source/whatsnew/v1.1.0.rst
@@ -309,6 +309,7 @@ Indexing
 - Bug in :meth:`DataFrame.iloc.__setitem__` on a :class:`DataFrame` with duplicate columns incorrectly setting values for all matching columns (:issue:`15686`, :issue:`22036`)
 - Bug in :meth:`DataFrame.loc:` and :meth:`Series.loc` with a :class:`DatetimeIndex`, :class:`TimedeltaIndex`, or :class:`PeriodIndex` incorrectly allowing lookups of non-matching datetime-like dtypes (:issue:`32650`)
 - Bug in :meth:`Series.__getitem__` indexing with non-standard scalars, e.g. ``np.dtype`` (:issue:`32684`)
+- Bug in :class:`Index` constructor where an unhelpful error message was raised for ``numpy`` scalars (:issue:`33017`)
 
 Missing
 ^^^^^^^
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index 83064fe22eaff..5b439a851a709 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -395,10 +395,10 @@ def __new__(
                 raise ValueError("Index data must be 1-dimensional")
             return cls._simple_new(subarr, name)
 
-        elif hasattr(data, "__array__"):
-            return Index(np.asarray(data), dtype=dtype, copy=copy, name=name, **kwargs)
         elif data is None or is_scalar(data):
             raise cls._scalar_data_error(data)
+        elif hasattr(data, "__array__"):
+            return Index(np.asarray(data), dtype=dtype, copy=copy, name=name, **kwargs)
         else:
             if tupleize_cols and is_list_like(data):
                 # GH21470: convert iterable to list before determining if empty
diff --git a/pandas/tests/indexes/base_class/test_constructors.py b/pandas/tests/indexes/base_class/test_constructors.py
index 9e6a8f34c135d..c4dc1548bd718 100644
--- a/pandas/tests/indexes/base_class/test_constructors.py
+++ b/pandas/tests/indexes/base_class/test_constructors.py
@@ -1,3 +1,4 @@
+import numpy as np
 import pytest
 
 from pandas import Index, MultiIndex
@@ -7,14 +8,15 @@ class TestIndexConstructor:
     # Tests for the Index constructor, specifically for cases that do
     #  not return a subclass
 
-    def test_constructor_corner(self):
+    @pytest.mark.parametrize("value", [1, [1, 2][0], np.array([1, 2])[0]])
+    def test_constructor_corner(self, value):
         # corner case
         msg = (
             r"Index\(\.\.\.\) must be called with a collection of some "
-            "kind, 0 was passed"
+            f"kind, {value} was passed"
         )
         with pytest.raises(TypeError, match=msg):
-            Index(0)
+            Index(value)
 
     @pytest.mark.parametrize("index_vals", [[("A", 1), "B"], ["B", ("A", 1)]])
     def test_construction_list_mixed_tuples(self, index_vals):


Code review comments:
diff_hunk: @@ -7,14 +8,15 @@ class TestIndexConstructor:
     # Tests for the Index constructor, specifically for cases that do
     #  not return a subclass
 
-    def test_constructor_corner(self):
+    @pytest.mark.parametrize("value", [1, [1, 2][0], np.array([1, 2])[0]])
path: pandas/tests/indexes/base_class/test_constructors.py
text: @user2:
```suggestion
    @user1.mark.parametrize("value", [1, np.int64(1)])
```

I think can simplify a bit further