Repository: pandas-dev/pandas (python)

Issue:
BUG: get_level_values() in a MultiIndex returns DatetimeIndex without frequency even though the index level has a frequency (and unique values).
### Pandas version checks

- [X] I have checked that this issue has not already been reported.

- [X] I have confirmed this bug exists on the [latest version](https://pandas.pydata.org/docs/whatsnew/index.html) of pandas.

- [X] I have confirmed this bug exists on the [main branch](https://pandas.pydata.org/docs/dev/getting_started/install.html#installing-the-development-version-of-pandas) of pandas.


### Reproducible Example

```python
>>> import pandas as pd
>>> dates  = pd.date_range("2000", freq = 'YS', periods = 4)
>>> index = ["A"]
>>> multi_index = pd.MultiIndex.from_product([dates, index], names = [“Dates”, “Second Index”])
>>> print(multi_index.levels[0].freq)
<YearBegin: month=1>
>>> print(multi_index.get_level_values(0).freq)
None
>>> print(multi_index.get_level_values(“Dates”).freq)
None
```


### Issue Description

For a DatetimeIndex contained in a MultiIndex get_level_values() returns a DatetimeIndex without frequency, even if the frequency is set and available in the internal structure (i.e. if accessed via index.levels, see example above).
 
The underlying issue seems to be the procedure in  _get_level_values(…) in index/multi.py :  When creating the object for the shallow copy a new DatetimeIndex is generated which does not carry along the DatetimeIndex frequency. 

Why (at least to me) it is important that this works correctly although it works with level[0].freq? With get_level_values() it is also possible to use the name as an identifier (not only the index level number), which in many cases is a lot more convenient. 


### Expected Behavior

I would expect that get_level_values() returns a DatetimeIndex with correct frequency, mirroring the one actually set in the MultiIndex.


### Installed Versions

<details>

------------------
commit                : d9cdd2ee5a58015ef6f4d15c7226110c9aab8140
python                : 3.9.13.final.0
python-bits           : 64
OS                    : Windows
OS-release            : 10
Version               : 10.0.19045
machine               : AMD64
processor             : Intel64 Family 6 Model 85 Stepping 0, GenuineIntel
byteorder             : little
LC_ALL                : None
LANG                  : None
LOCALE                : English_United Kingdom.1252
 
pandas                : 2.2.2
numpy                 : 1.26.4
pytz                  : 2024.1
dateutil              : 2.9.0.post0
setuptools            : 69.2.0
pip                   : 24.0
Cython                : None
pytest                : None
hypothesis            : None
sphinx                : None
blosc                 : None
feather               : None
xlsxwriter            : None
lxml.etree            : None
html5lib              : None
pymysql               : None
psycopg2              : None
jinja2                : None
IPython               : None
pandas_datareader     : None
adbc-driver-postgresql: None
adbc-driver-sqlite    : None
bs4                   : None
bottleneck            : None
dataframe-api-compat  : None
fastparquet           : None
fsspec                : None
gcsfs                 : None
matplotlib            : None
numba                 : None
numexpr               : None
odfpy                 : None
openpyxl              : None
pandas_gbq            : None
pyarrow               : None
pyreadstat            : None
python-calamine       : None
pyxlsb                : None
s3fs                  : None
scipy                 : None
sqlalchemy            : None
tables                : None
tabulate              : None
xarray                : None
xlrd                  : None
zstandard             : None
tzdata                : 2024.1
qtpy                  : None
pyqt5                 : None

<details>

Pull request:
BUG: Add frequency to DatetimeArray/TimedeltaArray take 
- [x] closes #58327 #57949
- [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.


<details> 
<summary> Disclaimer </summary>
I am required to add that the software is provided "as is", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose and noninfringement. In no event shall the authors or copyright holders be liable for any claim, damages or other liability, whether in an action of contract, tort or otherwise, arising from, out of or in connection with the software or the use or other dealings in the software.
</details> 


Patch:
diff --git a/doc/source/whatsnew/v3.0.0.rst b/doc/source/whatsnew/v3.0.0.rst
index cd91792488..639655ab28 100644
--- a/doc/source/whatsnew/v3.0.0.rst
+++ b/doc/source/whatsnew/v3.0.0.rst
@@ -556,6 +556,7 @@ MultiIndex
 - :func:`DataFrame.loc` with ``axis=0``  and :class:`MultiIndex` when setting a value adds extra columns (:issue:`58116`)
 - :meth:`DataFrame.melt` would not accept multiple names in ``var_name`` when the columns were a :class:`MultiIndex` (:issue:`58033`)
 - :meth:`MultiIndex.insert` would not insert NA value correctly at unified location of index -1 (:issue:`59003`)
+- :func:`MultiIndex.get_level_values` accessing a :class:`DatetimeIndex` does not carry the frequency attribute along (:issue:`58327`, :issue:`57949`)
 -
 
 I/O
diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py
index c90ff410b4..ad0bde3abb 100644
--- a/pandas/core/arrays/datetimelike.py
+++ b/pandas/core/arrays/datetimelike.py
@@ -65,6 +65,7 @@ from pandas._typing import (
     ScalarIndexer,
     Self,
     SequenceIndexer,
+    TakeIndexer,
     TimeAmbiguous,
     TimeNonexistent,
     npt,
@@ -2340,6 +2341,27 @@ class TimelikeOps(DatetimeLikeArrayMixin):
             return self
         return type(self)._simple_new(out_data, dtype=self.dtype)
 
+    def take(
+        self,
+        indices: TakeIndexer,
+        *,
+        allow_fill: bool = False,
+        fill_value: Any = None,
+        axis: AxisInt = 0,
+    ) -> Self:
+        result = super().take(
+            indices=indices, allow_fill=allow_fill, fill_value=fill_value, axis=axis
+        )
+
+        indices = np.asarray(indices, dtype=np.intp)
+        maybe_slice = lib.maybe_indices_to_slice(indices, len(self))
+
+        if isinstance(maybe_slice, slice):
+            freq = self._get_getitem_freq(maybe_slice)
+            result._freq = freq
+
+        return result
+
     # --------------------------------------------------------------
     # Unsorted
 
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 5ef663564a..9e0844f255 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -4554,8 +4554,8 @@ class DataFrame(NDFrame, OpsMixin):
         For example, ```it's` > `that's``` will raise an error,
         as it forms a quoted string (``'s > `that'``) with a backtick inside.
 
-        See also the Python documentation about lexical analysis
-        (https://docs.python.org/3/reference/lexical_analysis.html)
+        See also the `Python documentation about lexical analysis
+        <https://docs.python.org/3/reference/lexical_analysis.html>`__
         in combination with the source code in :mod:`pandas.core.computation.parsing`.
 
         Examples


Test patch:
diff --git a/pandas/tests/indexes/multi/test_get_level_values.py b/pandas/tests/indexes/multi/test_get_level_values.py
index 28c77e7892..4db74a716c 100644
--- a/pandas/tests/indexes/multi/test_get_level_values.py
+++ b/pandas/tests/indexes/multi/test_get_level_values.py
@@ -122,3 +122,12 @@ def test_values_loses_freq_of_underlying_index():
     midx.values
     assert idx.freq is not None
     tm.assert_index_equal(idx, expected)
+
+
+def test_get_level_values_gets_frequency_correctly():
+    # GH#57949 GH#58327
+    datetime_index = date_range(start=pd.to_datetime("1/1/2018"), periods=4, freq="YS")
+    other_index = ["A"]
+    multi_index = MultiIndex.from_product([datetime_index, other_index])
+
+    assert multi_index.get_level_values(0).freq == datetime_index.freq