From 59ea171c3b40097f1d55884ee550b7f0872abb59 Mon Sep 17 00:00:00 2001 From: Rahul Sathanapalli Date: Sat, 12 Dec 2020 04:34:18 +0530 Subject: [PATCH] ENH: Add MultiIndex.dtypes (#37073) --- doc/source/reference/indexing.rst | 1 + doc/source/whatsnew/v1.3.0.rst | 2 +- pandas/core/indexes/multi.py | 9 +++++++++ pandas/tests/indexes/multi/test_get_set.py | 18 ++++++++++++++++++ 4 files changed, 29 insertions(+), 1 deletion(-) diff --git a/doc/source/reference/indexing.rst b/doc/source/reference/indexing.rst index d3f9413dae565e..8446b384b8fb8c 100644 --- a/doc/source/reference/indexing.rst +++ b/doc/source/reference/indexing.rst @@ -290,6 +290,7 @@ MultiIndex properties MultiIndex.codes MultiIndex.nlevels MultiIndex.levshape + MultiIndex.dtypes MultiIndex components ~~~~~~~~~~~~~~~~~~~~~ diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index ae3ac44a8388cb..ab9f303bec6aaa 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -19,7 +19,7 @@ Enhancements Other enhancements ^^^^^^^^^^^^^^^^^^ -- +- Added :meth:`MultiIndex.dtypes` (:issue:`37062`) - .. --------------------------------------------------------------------------- diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index 75386a8779b200..cb0ca335f751fe 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -700,6 +700,15 @@ def array(self): "'MultiIndex.to_numpy()' to get a NumPy array of tuples." ) + @cache_readonly + def dtypes(self) -> "Series": + """ + Return the dtypes as a Series for the underlying MultiIndex + """ + from pandas import Series + + return Series({level.name: level.dtype for level in self.levels}) + @property def shape(self) -> Shape: """ diff --git a/pandas/tests/indexes/multi/test_get_set.py b/pandas/tests/indexes/multi/test_get_set.py index 63dd1b575284cf..83cebf90623feb 100644 --- a/pandas/tests/indexes/multi/test_get_set.py +++ b/pandas/tests/indexes/multi/test_get_set.py @@ -1,6 +1,8 @@ import numpy as np import pytest +from pandas.core.dtypes.dtypes import DatetimeTZDtype + import pandas as pd from pandas import CategoricalIndex, MultiIndex import pandas._testing as tm @@ -27,6 +29,22 @@ def test_get_level_number_integer(idx): idx._get_level_number("fourth") +def test_get_dtypes(): + # Test MultiIndex.dtypes (# Gh37062) + idx_multitype = MultiIndex.from_product( + [[1, 2, 3], ["a", "b", "c"], pd.date_range("20200101", periods=2, tz="UTC")], + names=["int", "string", "dt"], + ) + expected = pd.Series( + { + "int": np.dtype("int64"), + "string": np.dtype("O"), + "dt": DatetimeTZDtype(tz="utc"), + } + ) + tm.assert_series_equal(expected, idx_multitype.dtypes) + + def test_get_level_number_out_of_bounds(multiindex_dataframe_random_data): frame = multiindex_dataframe_random_data