Skip to content

Commit 1b03087

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

File tree

2 files changed

+21
-5
lines changed

2 files changed

+21
-5
lines changed

pandas/core/indexes/base.py

+12-5
Original file line numberDiff line numberDiff line change
@@ -112,10 +112,12 @@ 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
117117
tupleize_cols : bool (default: True)
118118
When True, attempt to create a MultiIndex if possible
119+
names : sequence of objects, optional
120+
Names for the index levels used when attempt to create a MultiIndex
119121
120122
Notes
121123
-----
@@ -177,10 +179,15 @@ class Index(IndexOpsMixin, PandasObject):
177179
str = accessor.AccessorProperty(strings.StringMethods)
178180

179181
def __new__(cls, data=None, dtype=None, copy=False, name=None,
180-
fastpath=False, tupleize_cols=True, **kwargs):
182+
fastpath=False, tupleize_cols=True, names=None,
183+
**kwargs):
181184

182-
if name is None and hasattr(data, 'name'):
183-
name = data.name
185+
if name is None:
186+
if hasattr(data, 'name'):
187+
name = data.name
188+
# extract `name` from `names` in case MultiIndex cannot be created
189+
elif names:
190+
name = names[0]
184191

185192
if fastpath:
186193
return cls._simple_new(data, name)
@@ -360,7 +367,7 @@ def __new__(cls, data=None, dtype=None, copy=False, name=None,
360367
if all(isinstance(e, tuple) for e in data):
361368
from .multi import MultiIndex
362369
return MultiIndex.from_tuples(
363-
data, names=name or kwargs.get('names'))
370+
data, names=names or kwargs.get('names') or name)
364371
# other iterable of some kind
365372
subarr = _asarray_tuplesafe(data, dtype=object)
366373
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)