Skip to content

BUG: MultiIndex.dtypes to handle when no level names #38582

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Dec 21, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion pandas/core/indexes/multi.py
Original file line number Diff line number Diff line change
Expand Up @@ -707,7 +707,12 @@ def dtypes(self) -> "Series":
"""
from pandas import Series

return Series({level.name: level.dtype for level in self.levels})
return Series(
{
f"level_{idx}" if level.name is None else level.name: level.dtype
for idx, level in enumerate(self.levels)
}
)

@property
def shape(self) -> Shape:
Expand Down
19 changes: 19 additions & 0 deletions pandas/tests/indexes/multi/test_get_set.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,25 @@ def test_get_dtypes():
tm.assert_series_equal(expected, idx_multitype.dtypes)


def test_get_dtypes_no_level_name():
# Test MultiIndex.dtypes (# GH38580 )
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit but I'd make this

# GH38580

idx_multitype = MultiIndex.from_product(
[
[1, 2, 3],
["a", "b", "c"],
pd.date_range("20200101", periods=2, tz="UTC"),
],
)
expected = pd.Series(
{
"level_0": np.dtype("int64"),
"level_1": np.dtype("O"),
"level_2": 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