Skip to content

Commit

Permalink
ENH: Add MultiIndex.dtypes (pandas-dev#37073)
Browse files Browse the repository at this point in the history
  • Loading branch information
skvrahul authored and luckyvs1 committed Jan 20, 2021
1 parent 554b932 commit 59ea171
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 1 deletion.
1 change: 1 addition & 0 deletions doc/source/reference/indexing.rst
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,7 @@ MultiIndex properties
MultiIndex.codes
MultiIndex.nlevels
MultiIndex.levshape
MultiIndex.dtypes

MultiIndex components
~~~~~~~~~~~~~~~~~~~~~
Expand Down
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v1.3.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ Enhancements
Other enhancements
^^^^^^^^^^^^^^^^^^

-
- Added :meth:`MultiIndex.dtypes` (:issue:`37062`)
-

.. ---------------------------------------------------------------------------
Expand Down
9 changes: 9 additions & 0 deletions pandas/core/indexes/multi.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
"""
Expand Down
18 changes: 18 additions & 0 deletions pandas/tests/indexes/multi/test_get_set.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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

Expand Down

0 comments on commit 59ea171

Please sign in to comment.