Skip to content

Commit aaecd93

Browse files
committed
modified: pandas/tests/reshape/test_pivot.py
- Added test :callable:`test_pivot_table_index_and_column_keys_with_nan` to test that null index/column keys are kept when `dropna=False`, and removed when `dropna=True`.
1 parent b64f438 commit aaecd93

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

pandas/tests/reshape/test_pivot.py

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2529,6 +2529,63 @@ def test_pivot_table_aggfunc_nunique_with_different_values(self):
25292529

25302530
tm.assert_frame_equal(result, expected)
25312531

2532+
def test_pivot_table_index_and_column_keys_with_nan(self, dropna: bool) -> None:
2533+
"""Index/column keys containing NA values depend on ``dropna``.
2534+
2535+
Input data
2536+
----------
2537+
row col val
2538+
0 NaN 0.0 0
2539+
1 0.0 1.0 1
2540+
2 1.0 2.0 2
2541+
3 2.0 3.0 3
2542+
4 3.0 NaN 4
2543+
2544+
``dropna=True``: Index/column keys containing NA values will be dropped.
2545+
Expected output
2546+
---------------
2547+
col 1.0 2.0 3.0
2548+
row
2549+
0.0 1.0 NaN NaN
2550+
1.0 NaN 2.0 NaN
2551+
2.0 NaN NaN 3.0
2552+
2553+
``dropna=False``: Index/columns should exist if any non-null values.
2554+
Expected output
2555+
---------------
2556+
col 0.0 1.0 2.0 3.0 NaN
2557+
row
2558+
0.0 NaN 1.0 NaN NaN NaN
2559+
1.0 NaN NaN 2.0 NaN NaN
2560+
2.0 NaN NaN NaN 3.0 NaN
2561+
3.0 NaN NaN NaN NaN 4.0
2562+
NaN 0.0 NaN NaN NaN NaN
2563+
"""
2564+
data = {"row": [None, *range(4)], "col": [*range(4), None], "val": range(5)}
2565+
df = DataFrame(data)
2566+
actual = df.pivot_table(values="val", index="row", columns="col", dropna=dropna)
2567+
e_index = [None, *range(4)]
2568+
e_columns = [*range(4), None]
2569+
e_data = np.zeros(shape=(5, 5))
2570+
e_data.fill(np.NaN)
2571+
np.fill_diagonal(a=e_data, val=range(5))
2572+
expected = DataFrame(
2573+
data=e_data,
2574+
index=Index(data=e_index, name="row"),
2575+
columns=Index(data=e_columns, name="col"),
2576+
).sort_index()
2577+
if dropna:
2578+
expected = (
2579+
# Drop null index/column keys.
2580+
expected.loc[expected.index.notna(), expected.columns.notna()]
2581+
# Drop null rows.
2582+
.dropna(axis="index", how="all")
2583+
# Drop null columns.
2584+
.dropna(axis="columns", how="all")
2585+
)
2586+
2587+
tm.assert_frame_equal(left=actual, right=expected)
2588+
25322589

25332590
class TestPivot:
25342591
def test_pivot(self):

0 commit comments

Comments
 (0)