Skip to content

Commit feaa503

Browse files
tanmay1618TomAugspurger
authored andcommitted
BUG: added missing fill_na parameter to DataFrame.unstack() with list of levels (#30838)
* added missing fill_na parameter
1 parent 0dc317f commit feaa503

File tree

3 files changed

+33
-1
lines changed

3 files changed

+33
-1
lines changed

doc/source/whatsnew/v1.0.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -1040,6 +1040,7 @@ Reshaping
10401040
- Dtypes are now preserved when transposing a ``DataFrame`` where each column is the same extension dtype (:issue:`30091`)
10411041
- Bug in :func:`merge_asof` merging on a tz-aware ``left_index`` and ``right_on`` a tz-aware column (:issue:`29864`)
10421042
- Improved error message and docstring in :func:`cut` and :func:`qcut` when `labels=True` (:issue:`13318`)
1043+
- Bug in missing `fill_na` parameter to :meth:`DataFrame.unstack` with list of levels (:issue:`30740`)
10431044

10441045
Sparse
10451046
^^^^^^

pandas/core/reshape/reshape.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -358,7 +358,7 @@ def _unstack_multiple(data, clocs, fill_value=None):
358358
result = data
359359
for i in range(len(clocs)):
360360
val = clocs[i]
361-
result = result.unstack(val)
361+
result = result.unstack(val, fill_value=fill_value)
362362
clocs = [v if i > v else v - 1 for v in clocs]
363363

364364
return result

pandas/tests/frame/test_reshape.py

+31
Original file line numberDiff line numberDiff line change
@@ -1128,3 +1128,34 @@ def test_stack_timezone_aware_values():
11281128
),
11291129
)
11301130
tm.assert_series_equal(result, expected)
1131+
1132+
1133+
def test_unstacking_multi_index_df():
1134+
# see gh-30740
1135+
df = DataFrame(
1136+
{
1137+
"name": ["Alice", "Bob"],
1138+
"score": [9.5, 8],
1139+
"employed": [False, True],
1140+
"kids": [0, 0],
1141+
"gender": ["female", "male"],
1142+
}
1143+
)
1144+
df = df.set_index(["name", "employed", "kids", "gender"])
1145+
df = df.unstack(["gender"], fill_value=0)
1146+
expected = df.unstack("employed", fill_value=0).unstack("kids", fill_value=0)
1147+
result = df.unstack(["employed", "kids"], fill_value=0)
1148+
expected = DataFrame(
1149+
[[9.5, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 8.0]],
1150+
index=Index(["Alice", "Bob"], name="name"),
1151+
columns=MultiIndex.from_tuples(
1152+
[
1153+
("score", "female", False, 0),
1154+
("score", "female", True, 0),
1155+
("score", "male", False, 0),
1156+
("score", "male", True, 0),
1157+
],
1158+
names=[None, "gender", "employed", "kids"],
1159+
),
1160+
)
1161+
tm.assert_frame_equal(result, expected)

0 commit comments

Comments
 (0)