@@ -1565,22 +1565,22 @@ def _unstack_once(
15651565 index : pd .MultiIndex ,
15661566 dim : Hashable ,
15671567 fill_value = dtypes .NA ,
1568- sparse = False ,
1568+ sparse : bool = False ,
15691569 ) -> "Variable" :
15701570 """
15711571 Unstacks this variable given an index to unstack and the name of the
15721572 dimension to which the index refers.
15731573 """
15741574
15751575 reordered = self .transpose (..., dim )
1576- shape = reordered . shape
1576+
15771577 new_dim_sizes = [lev .size for lev in index .levels ]
15781578 new_dim_names = index .names
15791579 indexer = index .codes
15801580
15811581 # Potentially we could replace `len(other_dims)` with just `-1`
15821582 other_dims = [d for d in self .dims if d != dim ]
1583- new_shape = tuple (list (shape [: len (other_dims )]) + new_dim_sizes )
1583+ new_shape = tuple (list (reordered . shape [: len (other_dims )]) + new_dim_sizes )
15841584 new_dims = reordered .dims [: len (other_dims )] + new_dim_names
15851585
15861586 if fill_value is dtypes .NA :
@@ -1594,14 +1594,17 @@ def _unstack_once(
15941594 dtype = self .dtype
15951595
15961596 if sparse :
1597+ # unstacking a dense multitindexed array to a sparse array
1598+ # Use the sparse.COO constructor until sparse supports advanced indexing
1599+ # https://github.com/pydata/sparse/issues/114
15971600 # TODO: how do we allow different sparse array types
15981601 from sparse import COO
15991602
16001603 codes = zip (* index .codes )
1601- if not shape [: - 1 ] :
1604+ if reordered . ndim == 1 :
16021605 indexes = codes
16031606 else :
1604- sizes = itertools .product (range (* shape [:- 1 ]))
1607+ sizes = itertools .product (range (* reordered . shape [:- 1 ]))
16051608 tuple_indexes = itertools .product (sizes , codes )
16061609 indexes = map (lambda x : list (itertools .chain (* x )), tuple_indexes ) # type: ignore
16071610
0 commit comments