Skip to content

Infer names in MultiIndex.from_product #27895

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

Closed
wants to merge 6 commits into from
Closed
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
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v1.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ Enhancements
Other enhancements
^^^^^^^^^^^^^^^^^^

-
- :meth:`MultiIndex.from_product` infers level names from inputs when not explicitly provided (:issue:`27292`)
-

.. _whatsnew_1000.api_breaking:
Expand Down
23 changes: 22 additions & 1 deletion pandas/core/indexes/multi.py
Original file line number Diff line number Diff line change
Expand Up @@ -508,7 +508,9 @@ def from_product(cls, iterables, sortorder=None, names=None):
Level of sortedness (must be lexicographically sorted by that
level).
names : list / sequence of str, optional
Names for the levels in the index.
Names for the levels in the index. If not provided, names
will be inferred from iterables if the elements of iterables
have a name attribute.

Returns
-------
Expand All @@ -526,6 +528,18 @@ def from_product(cls, iterables, sortorder=None, names=None):
>>> colors = ['green', 'purple']
>>> pd.MultiIndex.from_product([numbers, colors],
... names=['number', 'color'])
MultiIndex([(0, 'green'),
(0, 'purple'),
(1, 'green'),
(1, 'purple'),
(2, 'green'),
(2, 'purple')],
names=['number', 'color'])

>>> numbers = pd.Series([0, 1, 2], name='number')
>>> colors = pd.Series(['green', 'purple'], name='color')
>>> pd.MultiIndex.from_product([numbers, colors])
...
MultiIndex([(0, 'green'),
(0, 'purple'),
(1, 'green'),
Expand All @@ -541,6 +555,13 @@ def from_product(cls, iterables, sortorder=None, names=None):
elif is_iterator(iterables):
iterables = list(iterables)

# Infer names from iterable if attribute is available
if names is None:
names = [getattr(idx, "name", None) for idx in iterables]

if all(name is None for name in names):
names = None

codes, levels = _factorize_from_iterables(iterables)
codes = cartesian_product(codes)
return MultiIndex(levels, codes, sortorder=sortorder, names=names)
Expand Down
23 changes: 23 additions & 0 deletions pandas/tests/indexes/multi/test_constructor.py
Original file line number Diff line number Diff line change
Expand Up @@ -473,6 +473,29 @@ def test_from_product_datetimeindex():
tm.assert_numpy_array_equal(mi.values, etalon)


@pytest.mark.parametrize(
"a, b, expected_names",
[
(
pd.Series([1, 2, 3], name="foo"),
pd.Series(["a", "b"], name="bar"),
["foo", "bar"],
),
(pd.Series([1, 2, 3]), pd.Series(["a", "b"]), None),
(pd.Series([1, 2, 3], name="foo"), ["a", "b"], ["foo", None]),
([1, 2, 3], ["a", "b"], None),
],
)
def test_from_product_infers_partial_names(a, b, expected_names):
result = MultiIndex.from_product([a, b])
expected = MultiIndex(
levels=[[1, 2, 3], ["a", "b"]],
codes=[[0, 0, 1, 1, 2, 2], [0, 1, 0, 1, 0, 1]],
names=expected_names,
)
tm.assert_index_equal(result, expected)


@pytest.mark.parametrize("ordered", [False, True])
@pytest.mark.parametrize("f", [lambda x: x, lambda x: pd.Series(x), lambda x: x.values])
def test_from_product_index_series_categorical(ordered, f):
Expand Down