diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 4e098b2f8be9b..69c89635cc828 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -176,10 +176,12 @@ class Index(IndexOpsMixin, PandasObject): Otherwise, an error will be raised. copy : bool Make a copy of input ndarray - name : object + name : object, optional Name to be stored in the index tupleize_cols : bool (default: True) When True, attempt to create a MultiIndex if possible + names : tuple of objects, optional + Names to be stored in the index (only accepts tuple of length 1) See Also -------- @@ -261,10 +263,18 @@ def __new__( name=None, fastpath=None, tupleize_cols=True, + names=None, **kwargs ): - if name is None and hasattr(data, "name"): + if names is not None: + if name is not None: + raise TypeError("Using name and names is unsupported") + elif len(names) > 1: + raise TypeError("names must be list-like of size 1") + # infer name from names when MultiIndex cannot be created + name = names[0] + elif hasattr(data, "name") and name is None: name = data.name if fastpath is not None: @@ -492,9 +502,7 @@ def __new__( # 10697 from .multi import MultiIndex - return MultiIndex.from_tuples( - data, names=name or kwargs.get("names") - ) + return MultiIndex.from_tuples(data, names=names or name) # other iterable of some kind subarr = com.asarray_tuplesafe(data, dtype=object) return Index(subarr, dtype=dtype, copy=copy, name=name, **kwargs) diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index d1ed79118d2fa..d116b45e20121 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -371,6 +371,25 @@ def test_constructor_simple_new(self, vals, dtype): result = index._simple_new(index.values, dtype) tm.assert_index_equal(result, index) + def test_constructor_names(self): + # test both `name` and `names` + with pytest.raises(TypeError): + idx = Index([1, 2, 3], name="a", names=("a",)) + + # test list-like with length > 1 + with pytest.raises(TypeError): + idx = Index([1, 2, 3], names=("a", "b")) + + # test using `name` for a flat `Index` + idx = Index([1, 2, 3], name="a") + assert idx.name == "a" + assert idx.names == ("a",) + + # test using `names` for a flat `Index` + idx = Index([1, 2, 3], names=("a",)) + assert idx.name == "a" + assert idx.names == ("a",) + @pytest.mark.parametrize( "vals", [