@@ -358,6 +358,52 @@ def test_unstack(self):
358
358
# test that int32 work
359
359
self .ymd .astype (np .int32 ).unstack ()
360
360
361
+ def test_unstack_partial (self ):
362
+ # check for regressions on this issue: https://github.com/pandas-dev/pandas/issues/19351
363
+ # make sure DataFrame.unstack() works when its run on a subset of the DataFrame
364
+ # and the Index levels contain values that are not present in the subset
365
+ result1 = pd .DataFrame (
366
+ [[1 , 1 , None , None , 30.0 , None ], [2 , 2 , None , None , 30.0 , None ]],
367
+ columns = [u"ix1" , u"ix2" , u"col1" , u"col2" , u"col3" , u"col4" ],
368
+ ).set_index ([u"ix1" , "ix2" ])
369
+ result1 = result1 .iloc [1 :2 ].unstack ("ix2" )
370
+ expected1 = pd .DataFrame (
371
+ [[None , None , 30.0 , None ]],
372
+ columns = pd .MultiIndex .from_product (
373
+ [["col1" , "col2" , "col3" , "col4" ], [2 ]], names = [None , "ix2" ]
374
+ ),
375
+ index = pd .Index ([2 ], name = "ix1" ),
376
+ )
377
+ tm .assert_frame_equal (result1 , expected1 )
378
+
379
+ result2 = pd .DataFrame (
380
+ [[1 , 1 , None , None , 30.0 ], [2 , 2 , None , None , 30.0 ]],
381
+ columns = [u"ix1" , u"ix2" , u"col1" , u"col2" , u"col3" ],
382
+ ).set_index ([u"ix1" , "ix2" ])
383
+ result2 = result2 .iloc [1 :2 ].unstack ("ix2" )
384
+ expected2 = pd .DataFrame (
385
+ [[None , None , 30.0 ]],
386
+ columns = pd .MultiIndex .from_product (
387
+ [["col1" , "col2" , "col3" ], [2 ]], names = [None , "ix2" ]
388
+ ),
389
+ index = pd .Index ([2 ], name = "ix1" ),
390
+ )
391
+ tm .assert_frame_equal (result2 , expected2 )
392
+
393
+ result3 = pd .DataFrame (
394
+ [[1 , 1 , None , None , 30.0 ], [2 , None , None , None , 30.0 ]],
395
+ columns = [u"ix1" , u"ix2" , u"col1" , u"col2" , u"col3" ],
396
+ ).set_index ([u"ix1" , "ix2" ])
397
+ result3 = result3 .iloc [1 :2 ].unstack ("ix2" )
398
+ expected3 = pd .DataFrame (
399
+ [[None , None , 30.0 ]],
400
+ columns = pd .MultiIndex .from_product (
401
+ [["col1" , "col2" , "col3" ], [None ]], names = [None , "ix2" ]
402
+ ),
403
+ index = pd .Index ([2 ], name = "ix1" ),
404
+ )
405
+ tm .assert_frame_equal (result3 , expected3 )
406
+
361
407
def test_unstack_multiple_no_empty_columns (self ):
362
408
index = MultiIndex .from_tuples (
363
409
[(0 , "foo" , 0 ), (0 , "bar" , 0 ), (1 , "baz" , 1 ), (1 , "qux" , 1 )]
0 commit comments