diff --git a/pandas/core/index.py b/pandas/core/index.py index fd11cd7f598c3..e2dd996bd133f 100644 --- a/pandas/core/index.py +++ b/pandas/core/index.py @@ -976,7 +976,9 @@ def append(self, other): to_concat.append(other) for obj in to_concat: - if isinstance(obj, Index) and obj.name != name: + if (isinstance(obj, Index) and + obj.name != name and + obj.name is not None): name = None break diff --git a/pandas/tests/test_index.py b/pandas/tests/test_index.py index bb75b12754dca..e378e2ed4b93f 100644 --- a/pandas/tests/test_index.py +++ b/pandas/tests/test_index.py @@ -4075,6 +4075,19 @@ def test_groupby(self): exp = dict((key, [key]) for key in self.index) tm.assert_dict_equal(groups, exp) + def test_index_name_retained(self): + # GH9857 + result = pd.DataFrame({'x': [1, 2, 6], + 'y': [2, 2, 8], + 'z': [-5, 0, 5]}) + result = result.set_index('z') + result.loc[10] = [9, 10] + df_expected = pd.DataFrame({'x': [1, 2, 6, 9], + 'y': [2, 2, 8, 10], + 'z': [-5, 0, 5, 10]}) + df_expected = df_expected.set_index('z') + tm.assert_frame_equal(result, df_expected) + def test_get_combined_index(): from pandas.core.index import _get_combined_index