diff --git a/pandas/core/construction.py b/pandas/core/construction.py index 387df6c6a6b70..89591f27e9092 100644 --- a/pandas/core/construction.py +++ b/pandas/core/construction.py @@ -405,9 +405,7 @@ def extract_array( For an ndarray-backed Series / Index a PandasArray is returned. >>> extract_array(pd.Series([1, 2, 3])) - - [1, 2, 3] - Length: 3, dtype: int64 + array([1, 2, 3]) To extract all the way down to the ndarray, pass ``extract_numpy=True``. diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 5f12a918c0520..54271f0f9b492 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -5406,6 +5406,9 @@ def _get_indexer_strict(self, key, axis_name: str_t) -> tuple[Index, np.ndarray] self._raise_if_missing(keyarr, indexer, axis_name) keyarr = self.take(indexer) + if isinstance(key, Index): + # GH 42790 - Preserve name from an Index + keyarr.name = key.name if keyarr.dtype.kind in ["m", "M"]: # DTI/TDI.take can infer a freq in some cases when we dont want one if isinstance(key, list) or ( diff --git a/pandas/tests/indexing/test_loc.py b/pandas/tests/indexing/test_loc.py index 9d52e8ab25306..6692a06c79d45 100644 --- a/pandas/tests/indexing/test_loc.py +++ b/pandas/tests/indexing/test_loc.py @@ -2432,6 +2432,18 @@ def test_loc_getitem_listlike_of_datetimelike_keys(self, to_period): with pytest.raises(KeyError, match="not in index"): ser.loc[keys] + def test_loc_named_index(self): + # GH 42790 + df = DataFrame( + [[1, 2], [4, 5], [7, 8]], + index=["cobra", "viper", "sidewinder"], + columns=["max_speed", "shield"], + ) + expected = df.iloc[:2] + expected.index.name = "foo" + result = df.loc[Index(["cobra", "viper"], name="foo")] + tm.assert_frame_equal(result, expected) + @pytest.mark.parametrize( "columns, column_key, expected_columns",