|
2 | 2 | import pytest
|
3 | 3 |
|
4 | 4 | import pandas as pd
|
5 |
| -from pandas import Index, MultiIndex |
| 5 | +from pandas import Index, Int64Index, MultiIndex |
6 | 6 | import pandas._testing as tm
|
7 | 7 |
|
8 | 8 |
|
@@ -190,3 +190,35 @@ def test_pivot_list_like_columns(
|
190 | 190 | expected_values, columns=expected_columns, index=expected_index
|
191 | 191 | )
|
192 | 192 | tm.assert_frame_equal(result, expected)
|
| 193 | + |
| 194 | + |
| 195 | +def test_pivot_multiindexed_rows_and_cols(): |
| 196 | + # GH 36360 |
| 197 | + |
| 198 | + df = pd.DataFrame( |
| 199 | + data=np.arange(12).reshape(4, 3), |
| 200 | + columns=MultiIndex.from_tuples( |
| 201 | + [(0, 0), (0, 1), (0, 2)], names=["col_L0", "col_L1"] |
| 202 | + ), |
| 203 | + index=MultiIndex.from_tuples( |
| 204 | + [(0, 0, 0), (0, 0, 1), (1, 1, 1), (1, 0, 0)], |
| 205 | + names=["idx_L0", "idx_L1", "idx_L2"], |
| 206 | + ), |
| 207 | + ) |
| 208 | + |
| 209 | + res = df.pivot_table( |
| 210 | + index=["idx_L0"], |
| 211 | + columns=["idx_L1"], |
| 212 | + values=[(0, 1)], |
| 213 | + aggfunc=lambda col: col.values.sum(), |
| 214 | + ) |
| 215 | + |
| 216 | + expected = pd.DataFrame( |
| 217 | + data=[[5.0, np.nan], [10.0, 7.0]], |
| 218 | + columns=MultiIndex.from_tuples( |
| 219 | + [(0, 1, 0), (0, 1, 1)], names=["col_L0", "col_L1", "idx_L1"] |
| 220 | + ), |
| 221 | + index=Int64Index([0, 1], dtype="int64", name="idx_L0"), |
| 222 | + ) |
| 223 | + |
| 224 | + tm.assert_frame_equal(res, expected) |
0 commit comments