Skip to content

Commit e12bca1

Browse files
committed
ENH: allow tuple index names to be interpreted as full column keys
1 parent 6315d07 commit e12bca1

File tree

3 files changed

+9
-6
lines changed

3 files changed

+9
-6
lines changed

doc/source/whatsnew/v0.20.0.txt

+1
Original file line numberDiff line numberDiff line change
@@ -490,6 +490,7 @@ Other Enhancements
490490
- ``Series.interpolate()`` now supports timedelta as an index type with ``method='time'`` (:issue:`6424`)
491491
- Addition of a ``level`` keyword to ``DataFrame/Series.rename`` to rename
492492
labels in the specified level of a MultiIndex (:issue:`4160`).
493+
- ``DataFrame.reset_index()`` will now interpret a tuple ``index.name`` as a key spanning across levels of ``columns``, if this is a ``MultiIndex`` (:issues:`16164`)
493494
- ``Timedelta.isoformat`` method added for formatting Timedeltas as an `ISO 8601 duration`_. See the :ref:`Timedelta docs <timedeltas.isoformat>` (:issue:`15136`)
494495
- ``.select_dtypes()`` now allows the string ``datetimetz`` to generically select datetimes with tz (:issue:`14910`)
495496
- The ``.to_latex()`` method will now accept ``multicolumn`` and ``multirow`` arguments to use the accompanying LaTeX enhancements

pandas/core/frame.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -3034,7 +3034,7 @@ def _maybe_casted_values(index, labels=None):
30343034
for i, (lev, lab) in reversed(list(enumerate(to_insert))):
30353035
col_name = names[i]
30363036

3037-
if multi_col:
3037+
if multi_col and not isinstance(col_name, tuple):
30383038
if col_fill is None:
30393039
col_name = tuple([col_name] * self.columns.nlevels)
30403040
else:

pandas/tests/test_multilevel.py

100755100644
+7-5
Original file line numberDiff line numberDiff line change
@@ -2242,16 +2242,18 @@ def test_reset_index_multiindex_columns(self):
22422242
levels = [['A', ''], ['B', 'b']]
22432243
df = pd.DataFrame([[0, 2], [1, 3]],
22442244
columns=pd.MultiIndex.from_tuples(levels))
2245-
expected = df.copy()
2246-
df.index.name = 'A'
2247-
result = df[['B']].reset_index()
2248-
tm.assert_frame_equal(result, expected)
2245+
result = df[['B']].rename_axis('A').reset_index()
2246+
tm.assert_frame_equal(result, df)
22492247

22502248
# gh-16120: already existing column
22512249
with tm.assert_raises_regex(ValueError,
22522250
("cannot insert \('A', ''\), "
22532251
"already exists")):
2254-
df.reset_index()
2252+
df.rename_axis('A').reset_index()
2253+
2254+
# gh-16164: multiindex (tuple) full key
2255+
result = df.set_index([('A', '')]).reset_index()
2256+
tm.assert_frame_equal(result, df)
22552257

22562258
def test_set_index_period(self):
22572259
# GH 6631

0 commit comments

Comments
 (0)