From f5b28574fa01fd712d8893799dde7619a76bd78b Mon Sep 17 00:00:00 2001 From: tadamcz Date: Sun, 21 Jul 2024 14:47:28 +0100 Subject: [PATCH] allow set_index to set a multiindex from a tuple, not just a list --- pandas/core/frame.py | 2 +- pandas/tests/copy_view/index/test_index.py | 15 +++++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/pandas/core/frame.py b/pandas/core/frame.py index ee48f546815bb..58759805d02c4 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -5913,7 +5913,7 @@ def set_index( """ inplace = validate_bool_kwarg(inplace, "inplace") self._check_inplace_and_allows_duplicate_labels(inplace) - if not isinstance(keys, list): + if not is_list_like(keys): keys = [keys] err_msg = ( diff --git a/pandas/tests/copy_view/index/test_index.py b/pandas/tests/copy_view/index/test_index.py index e51f5658cf437..87f2049dfd1f0 100644 --- a/pandas/tests/copy_view/index/test_index.py +++ b/pandas/tests/copy_view/index/test_index.py @@ -44,6 +44,21 @@ def test_set_index_series(): ser.iloc[0] = 100 tm.assert_index_equal(df.index, expected) +class TestSetMultiIndex: + df = DataFrame({"a": [1, 2], "b": 1.5, "c": [3, 4]}) + + def test_from_list(self): + df = self.df.set_index(["a", "b"]) + self._assert(df) + + def test_from_tuple(self): + df = self.df.set_index(("a", "b")) + self._assert(df) + + def _assert(self, df): + assert isinstance(df.index, pd.MultiIndex) + assert df.index.names == ["a", "b"] + def test_assign_index_as_series(): df = DataFrame({"a": [1, 2], "b": 1.5})