Skip to content

Commit fc40dcc

Browse files
Gianluca Rossijreback
Gianluca Rossi
authored andcommitted
BUG: Index does not copy existing Index or DatatetimeIndex object's name, when a new name is not provided, #11193
fix missing lines in whatsnew cosmetic change in whatsnew refactor unit test, failing for MultiIndex short sentence in whatsnew doc fix unit test remove commented code fix typo add doc string add unit test for multiindex case
1 parent 71f652d commit fc40dcc

File tree

4 files changed

+36
-2
lines changed

4 files changed

+36
-2
lines changed

doc/source/whatsnew/v0.18.0.txt

+2
Original file line numberDiff line numberDiff line change
@@ -238,4 +238,6 @@ Bug Fixes
238238

239239
- Bug in ``df.replace`` while replacing value in mixed dtype ``Dataframe`` (:issue:`11698`)
240240

241+
- Bug in ``Index`` prevents copying name of passed ``Index``, when a new name is not provided (:issue:`11193`)
242+
241243
- Bug in ``read_excel`` failing to read any non-empty sheets when empty sheets exist and ``sheetname=None`` (:issue:`11711`)

pandas/core/index.py

+4
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,9 @@ class Index(IndexOpsMixin, StringAccessorMixin, PandasObject):
120120
def __new__(cls, data=None, dtype=None, copy=False, name=None, fastpath=False,
121121
tupleize_cols=True, **kwargs):
122122

123+
if name is None and hasattr(data, 'name'):
124+
name = data.name
125+
123126
# no class inference!
124127
if fastpath:
125128
return cls._simple_new(data, name)
@@ -128,6 +131,7 @@ def __new__(cls, data=None, dtype=None, copy=False, name=None, fastpath=False,
128131
return CategoricalIndex(data, copy=copy, name=name, **kwargs)
129132

130133
if isinstance(data, (np.ndarray, Index, ABCSeries)):
134+
131135
if issubclass(data.dtype.type, np.datetime64) or is_datetimetz(data):
132136
from pandas.tseries.index import DatetimeIndex
133137
result = DatetimeIndex(data, copy=copy, name=name, **kwargs)

pandas/tests/test_base.py

+4-1
Original file line numberDiff line numberDiff line change
@@ -415,6 +415,7 @@ def test_value_counts_unique_nunique(self):
415415

416416
# resets name from Index
417417
expected_index = pd.Index(o[::-1])
418+
expected_index.name = None
418419

419420
# attach name to klass
420421
o = o.repeat(range(1, len(o) + 1))
@@ -424,16 +425,18 @@ def test_value_counts_unique_nunique(self):
424425

425426
# resets name from Index
426427
expected_index = pd.Index(o[::-1])
428+
expected_index.name = None
427429

428430
# attach name to klass
429431
o = o.repeat(range(1, len(o) + 1))
430432
o.name = 'a'
431433

432434
# don't test boolean
433-
elif isinstance(o,Index) and o.is_boolean():
435+
elif isinstance(o, Index) and o.is_boolean():
434436
continue
435437
elif isinstance(o, Index):
436438
expected_index = pd.Index(values[::-1])
439+
expected_index.name = None
437440
o = o.repeat(range(1, len(o) + 1))
438441
o.name = 'a'
439442
else:

pandas/tests/test_index.py

+26-1
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,31 @@ def test_shift(self):
6060
self.assertRaises(NotImplementedError, idx.shift, 1)
6161
self.assertRaises(NotImplementedError, idx.shift, 1, 2)
6262

63+
def test_create_index_existing_name(self):
64+
65+
# GH11193, when an existing index is passed, and a new name is not specified, the new index should inherit the
66+
# previous object name
67+
expected = self.create_index()
68+
if not isinstance(expected, MultiIndex):
69+
expected.name = 'foo'
70+
result = pd.Index(expected)
71+
tm.assert_index_equal(result, expected)
72+
73+
result = pd.Index(expected, name='bar')
74+
expected.name = 'bar'
75+
tm.assert_index_equal(result, expected)
76+
else:
77+
expected.names = ['foo', 'bar']
78+
result = pd.Index(expected)
79+
tm.assert_index_equal(result, Index(Index([('foo', 'one'), ('foo', 'two'), ('bar', 'one'), ('baz', 'two'),
80+
('qux', 'one'), ('qux', 'two')], dtype='object'),
81+
names=['foo', 'bar']))
82+
83+
result = pd.Index(expected, names=['A', 'B'])
84+
tm.assert_index_equal(result, Index(Index([('foo', 'one'), ('foo', 'two'), ('bar', 'one'), ('baz', 'two'),
85+
('qux', 'one'), ('qux', 'two')], dtype='object'),
86+
names=['A', 'B']))
87+
6388
def test_numeric_compat(self):
6489

6590
idx = self.create_index()
@@ -3043,7 +3068,7 @@ def test_identical(self):
30433068
i = self.index.copy(dtype=object)
30443069
i = i.rename('foo')
30453070
same_values = Index(i, dtype=object)
3046-
self.assertTrue(same_values.identical(self.index.copy(dtype=object)))
3071+
self.assertTrue(same_values.identical(i))
30473072

30483073
self.assertFalse(i.identical(self.index))
30493074
self.assertTrue(Index(same_values, name='foo', dtype=object

0 commit comments

Comments
 (0)