Skip to content

Commit 0fbbbbd

Browse files
committed
DataFrame pivot_table nunique aggfunc test GH#29080
Signed-off-by: Liang Yan <[email protected]>
1 parent 900ffa3 commit 0fbbbbd

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

pandas/tests/reshape/test_pivot.py

+55
Original file line numberDiff line numberDiff line change
@@ -2378,6 +2378,61 @@ def test_pivot_table_with_mixed_nested_tuples(self, using_array_manager):
23782378
expected["small"] = expected["small"].astype("int64")
23792379
tm.assert_frame_equal(result, expected)
23802380

2381+
def test_pivot_table_aggfunc_nunique_with_different_values(self):
2382+
np.random.seed(0)
2383+
test = DataFrame(
2384+
{
2385+
"a": np.random.randint(0, 10, size=(10,)),
2386+
"b": np.random.randint(0, 10, size=(10,)),
2387+
"c": np.random.randint(0, 10, size=(10,)),
2388+
"d": np.random.randint(0, 10, size=(10,)),
2389+
}
2390+
)
2391+
a = test["a"]
2392+
b = test["b"]
2393+
c = test["c"]
2394+
dictionary = {}
2395+
for x, y, z in np.nditer([a, b, c]):
2396+
xv = x.item()
2397+
yv = y.item()
2398+
zv = z.item()
2399+
if (xv, yv) in dictionary:
2400+
dictionary[(xv, yv)] += [zv]
2401+
else:
2402+
dictionary[(xv, yv)] = [zv]
2403+
2404+
for key in dictionary:
2405+
dictionary[key] = float(len(set(dictionary[key])))
2406+
2407+
indarr = np.sort(a.unique())
2408+
barr = np.sort(b.unique())
2409+
columnval = MultiIndex.from_arrays(
2410+
[
2411+
["nunique" for i in range(barr.size)],
2412+
["c" for i in range(barr.size)],
2413+
barr,
2414+
],
2415+
names=(None, None, "b"),
2416+
)
2417+
nparr = np.full((indarr.size, barr.size), np.NaN)
2418+
expected = DataFrame(nparr, index=Index(indarr, name="a"), columns=columnval)
2419+
for key, value in dictionary.items():
2420+
expected.loc[key[0], ("nunique", "c", key[1])] = value
2421+
result = test.pivot_table(
2422+
index=[
2423+
"a",
2424+
],
2425+
columns=[
2426+
"b",
2427+
],
2428+
values=[
2429+
"c",
2430+
],
2431+
aggfunc=["nunique"],
2432+
)
2433+
2434+
tm.assert_frame_equal(result, expected)
2435+
23812436

23822437
class TestPivot:
23832438
def test_pivot(self):

0 commit comments

Comments
 (0)