Skip to content

Commit 91dcad8

Browse files
committed
BUG: Creating Index with the names argument
1 parent 78147e9 commit 91dcad8

File tree

2 files changed

+27
-6
lines changed

2 files changed

+27
-6
lines changed

pandas/core/indexes/base.py

+18-6
Original file line numberDiff line numberDiff line change
@@ -112,14 +112,18 @@ class Index(IndexOpsMixin, PandasObject):
112112
dtype : NumPy dtype (default: object)
113113
copy : bool
114114
Make a copy of input ndarray
115-
name : object
115+
name : object, optional
116116
Name to be stored in the index
117+
names : sequence of objects, optional
118+
Names for the index levels used when attempt to create a MultiIndex
117119
tupleize_cols : bool (default: True)
118120
When True, attempt to create a MultiIndex if possible
119121
120122
Notes
121123
-----
122-
An Index instance can **only** contain hashable objects
124+
An Index instance can **only** contain hashable objects.
125+
126+
Only one of `name` and `names` can be specified at the same time.
123127
124128
Examples
125129
--------
@@ -177,10 +181,18 @@ class Index(IndexOpsMixin, PandasObject):
177181
str = accessor.AccessorProperty(strings.StringMethods)
178182

179183
def __new__(cls, data=None, dtype=None, copy=False, name=None,
180-
fastpath=False, tupleize_cols=True, **kwargs):
184+
fastpath=False, tupleize_cols=True, names=None,
185+
**kwargs):
181186

182-
if name is None and hasattr(data, 'name'):
183-
name = data.name
187+
if names is not None and name is not None:
188+
raise TypeError("Can only provide one of `names` and `name`")
189+
190+
if name is None:
191+
if hasattr(data, 'name'):
192+
name = data.name
193+
# extract `name` from `names` in case MultiIndex cannot be created
194+
elif names:
195+
name = names[0] if is_list_like(names) else names
184196

185197
if fastpath:
186198
return cls._simple_new(data, name)
@@ -360,7 +372,7 @@ def __new__(cls, data=None, dtype=None, copy=False, name=None,
360372
if all(isinstance(e, tuple) for e in data):
361373
from .multi import MultiIndex
362374
return MultiIndex.from_tuples(
363-
data, names=name or kwargs.get('names'))
375+
data, names=names or kwargs.get('names') or name)
364376
# other iterable of some kind
365377
subarr = _asarray_tuplesafe(data, dtype=object)
366378
return Index(subarr, dtype=dtype, copy=copy, name=name, **kwargs)

pandas/tests/indexes/test_base.py

+9
Original file line numberDiff line numberDiff line change
@@ -305,6 +305,15 @@ def test_constructor_simple_new(self):
305305
result = idx._simple_new(idx, 'obj')
306306
tm.assert_index_equal(result, idx)
307307

308+
def test_constructor_names(self):
309+
idx = Index([1, 2, 3], name='a')
310+
assert idx.name == 'a'
311+
assert idx.names == ('a',)
312+
313+
idx = Index([1, 2, 3], names=('a',))
314+
assert idx.name == 'a'
315+
assert idx.names == ('a',)
316+
308317
def test_constructor_dtypes(self):
309318

310319
for idx in [Index(np.array([1, 2, 3], dtype=int)),

0 commit comments

Comments
 (0)