MCPcopy
hub / github.com/pandas-dev/pandas / unstack

Method unstack

pandas/core/internals/managers.py:1748–1807  ·  view source on GitHub ↗

Return a BlockManager with all blocks unstacked. Parameters ---------- unstacker : reshape._Unstacker fill_value : Any fill_value for newly introduced missing values. Returns ------- unstacked : BlockManager

(self, unstacker, fill_value)

Source from the content-addressed store, hash-verified

1746 # ----------------------------------------------------------------
1747
1748 def unstack(self, unstacker, fill_value) -> BlockManager:
1749 """
1750 Return a BlockManager with all blocks unstacked.
1751
1752 Parameters
1753 ----------
1754 unstacker : reshape._Unstacker
1755 fill_value : Any
1756 fill_value for newly introduced missing values.
1757
1758 Returns
1759 -------
1760 unstacked : BlockManager
1761 """
1762 new_columns = unstacker.get_new_columns(self.items)
1763 new_index = unstacker.new_index
1764
1765 allow_fill = not unstacker.mask_all
1766 if allow_fill:
1767 # calculating the full mask once and passing it to Block._unstack is
1768 # faster than letting calculating it in each repeated call
1769 new_mask2D = (~unstacker.mask).reshape(*unstacker.full_shape)
1770 needs_masking = new_mask2D.any(axis=0)
1771 else:
1772 needs_masking = np.zeros(unstacker.full_shape[1], dtype=bool)
1773
1774 new_blocks: list[Block] = []
1775 columns_mask: list[np.ndarray] = []
1776
1777 if len(self.items) == 0:
1778 factor = 1
1779 else:
1780 fac = len(new_columns) / len(self.items)
1781 assert fac == int(fac)
1782 factor = int(fac)
1783
1784 for blk in self.blocks:
1785 mgr_locs = blk.mgr_locs
1786 new_placement = mgr_locs.tile_for_unstack(factor)
1787
1788 blocks, mask = blk._unstack(
1789 unstacker,
1790 fill_value,
1791 new_placement=new_placement,
1792 needs_masking=needs_masking,
1793 )
1794
1795 new_blocks.extend(blocks)
1796 columns_mask.extend(mask)
1797
1798 # Block._unstack should ensure this holds,
1799 assert mask.sum() == sum(len(nb._mgr_locs) for nb in blocks)
1800 # In turn this ensures that in the BlockManager call below
1801 # we have len(new_columns) == sum(x.shape[0] for x in new_blocks)
1802 # which suffices to allow us to pass verify_inegrity=False
1803
1804 new_columns = new_columns[columns_mask]
1805

Callers 7

__internal_pivot_tableFunction · 0.45
pivotFunction · 0.45
get_new_valuesMethod · 0.45
_unstack_multipleFunction · 0.45
_unstack_frameFunction · 0.45
describeMethod · 0.45

Calls 7

sumFunction · 0.85
BlockManagerClass · 0.85
get_new_columnsMethod · 0.80
reshapeMethod · 0.45
anyMethod · 0.45
_unstackMethod · 0.45
sumMethod · 0.45

Tested by

no test coverage detected