@@ -2378,6 +2378,61 @@ def test_pivot_table_with_mixed_nested_tuples(self, using_array_manager):
2378
2378
expected ["small" ] = expected ["small" ].astype ("int64" )
2379
2379
tm .assert_frame_equal (result , expected )
2380
2380
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
+
2381
2436
2382
2437
class TestPivot :
2383
2438
def test_pivot (self ):
0 commit comments