()
| 25 | |
| 26 | |
| 27 | def test_unstack(): |
| 28 | index = MultiIndex( |
| 29 | levels=[["bar", "foo"], ["one", "three", "two"]], |
| 30 | codes=[[1, 1, 0, 0], [0, 1, 0, 2]], |
| 31 | ) |
| 32 | |
| 33 | s = Series(np.arange(4.0), index=index) |
| 34 | unstacked = s.unstack() |
| 35 | |
| 36 | expected = DataFrame( |
| 37 | [[2.0, np.nan, 3.0], [0.0, 1.0, np.nan]], |
| 38 | index=["bar", "foo"], |
| 39 | columns=["one", "three", "two"], |
| 40 | ) |
| 41 | |
| 42 | tm.assert_frame_equal(unstacked, expected) |
| 43 | |
| 44 | unstacked = s.unstack(level=0) |
| 45 | tm.assert_frame_equal(unstacked, expected.T) |
| 46 | |
| 47 | index = MultiIndex( |
| 48 | levels=[["bar"], ["one", "two", "three"], [0, 1]], |
| 49 | codes=[[0, 0, 0, 0, 0, 0], [0, 1, 2, 0, 1, 2], [0, 1, 0, 1, 0, 1]], |
| 50 | ) |
| 51 | s = Series(np.random.default_rng(2).standard_normal(6), index=index) |
| 52 | exp_index = MultiIndex( |
| 53 | levels=[["one", "two", "three"], [0, 1]], |
| 54 | codes=[[0, 1, 2, 0, 1, 2], [0, 1, 0, 1, 0, 1]], |
| 55 | ) |
| 56 | expected = DataFrame({"bar": s.values}, index=exp_index).sort_index(level=0) |
| 57 | unstacked = s.unstack(0).sort_index() |
| 58 | tm.assert_frame_equal(unstacked, expected) |
| 59 | |
| 60 | # GH5873 |
| 61 | idx = MultiIndex.from_arrays([[101, 102], [3.5, np.nan]]) |
| 62 | ts = Series([1, 2], index=idx) |
| 63 | left = ts.unstack() |
| 64 | right = DataFrame( |
| 65 | [[np.nan, 1], [2, np.nan]], index=[101, 102], columns=[np.nan, 3.5] |
| 66 | ) |
| 67 | tm.assert_frame_equal(left, right) |
| 68 | |
| 69 | idx = MultiIndex.from_arrays( |
| 70 | [ |
| 71 | ["cat", "cat", "cat", "dog", "dog"], |
| 72 | ["a", "a", "b", "a", "b"], |
| 73 | [1, 2, 1, 1, np.nan], |
| 74 | ] |
| 75 | ) |
| 76 | ts = Series([1.0, 1.1, 1.2, 1.3, 1.4], index=idx) |
| 77 | right = DataFrame( |
| 78 | [[1.0, 1.3], [1.1, np.nan], [np.nan, 1.4], [1.2, np.nan]], |
| 79 | columns=["cat", "dog"], |
| 80 | ) |
| 81 | tpls = [("a", 1), ("a", 2), ("b", np.nan), ("b", 1)] |
| 82 | right.index = MultiIndex.from_tuples(tpls) |
| 83 | tm.assert_frame_equal(ts.unstack(level=0), right) |
| 84 |
nothing calls this directly
no test coverage detected