5353
5454import pandas .core .algorithms as algos
5555from pandas .core .arrays .sparse import SparseDtype
56- from pandas .core .construction import extract_array
56+ from pandas .core .construction import (
57+ ensure_wrapped_if_datetimelike ,
58+ extract_array ,
59+ )
5760from pandas .core .indexers import maybe_convert_indices
5861from pandas .core .indexes .api import (
5962 Float64Index ,
@@ -991,6 +994,8 @@ def fast_xs(self, loc: int) -> ArrayLike:
991994 # Any]]"
992995 result = np .empty (n , dtype = dtype ) # type: ignore[arg-type]
993996
997+ result = ensure_wrapped_if_datetimelike (result )
998+
994999 for blk in self .blocks :
9951000 # Such assignment may incorrectly coerce NaT to None
9961001 # result[blk.mgr_locs] = blk._slice((slice(None), loc))
@@ -1693,7 +1698,7 @@ def set_values(self, values: ArrayLike):
16931698
16941699
16951700def create_block_manager_from_blocks (
1696- blocks : List [Block ], axes : List [Index ]
1701+ blocks : List [Block ], axes : List [Index ], consolidate : bool = True
16971702) -> BlockManager :
16981703 try :
16991704 mgr = BlockManager (blocks , axes )
@@ -1703,7 +1708,8 @@ def create_block_manager_from_blocks(
17031708 tot_items = sum (arr .shape [0 ] for arr in arrays )
17041709 raise construction_error (tot_items , arrays [0 ].shape [1 :], axes , err )
17051710
1706- mgr ._consolidate_inplace ()
1711+ if consolidate :
1712+ mgr ._consolidate_inplace ()
17071713 return mgr
17081714
17091715
@@ -1713,7 +1719,10 @@ def _extract_array(obj):
17131719
17141720
17151721def create_block_manager_from_arrays (
1716- arrays , names : Index , axes : List [Index ]
1722+ arrays ,
1723+ names : Index ,
1724+ axes : List [Index ],
1725+ consolidate : bool = True ,
17171726) -> BlockManager :
17181727 assert isinstance (names , Index )
17191728 assert isinstance (axes , list )
@@ -1722,12 +1731,13 @@ def create_block_manager_from_arrays(
17221731 arrays = [_extract_array (x ) for x in arrays ]
17231732
17241733 try :
1725- blocks = _form_blocks (arrays , names , axes )
1734+ blocks = _form_blocks (arrays , names , axes , consolidate )
17261735 mgr = BlockManager (blocks , axes )
1727- mgr ._consolidate_inplace ()
1728- return mgr
17291736 except ValueError as e :
17301737 raise construction_error (len (arrays ), arrays [0 ].shape , axes , e )
1738+ if consolidate :
1739+ mgr ._consolidate_inplace ()
1740+ return mgr
17311741
17321742
17331743def construction_error (
@@ -1760,7 +1770,7 @@ def construction_error(
17601770
17611771
17621772def _form_blocks (
1763- arrays : List [ArrayLike ], names : Index , axes : List [Index ]
1773+ arrays : List [ArrayLike ], names : Index , axes : List [Index ], consolidate : bool
17641774) -> List [Block ]:
17651775 # put "leftover" items in float bucket, where else?
17661776 # generalize?
@@ -1786,15 +1796,21 @@ def _form_blocks(
17861796
17871797 blocks : List [Block ] = []
17881798 if len (items_dict ["NumericBlock" ]):
1789- numeric_blocks = _multi_blockify (items_dict ["NumericBlock" ])
1799+ numeric_blocks = _multi_blockify (
1800+ items_dict ["NumericBlock" ], consolidate = consolidate
1801+ )
17901802 blocks .extend (numeric_blocks )
17911803
17921804 if len (items_dict ["TimeDeltaBlock" ]):
1793- timedelta_blocks = _multi_blockify (items_dict ["TimeDeltaBlock" ])
1805+ timedelta_blocks = _multi_blockify (
1806+ items_dict ["TimeDeltaBlock" ], consolidate = consolidate
1807+ )
17941808 blocks .extend (timedelta_blocks )
17951809
17961810 if len (items_dict ["DatetimeBlock" ]):
1797- datetime_blocks = _simple_blockify (items_dict ["DatetimeBlock" ], DT64NS_DTYPE )
1811+ datetime_blocks = _simple_blockify (
1812+ items_dict ["DatetimeBlock" ], DT64NS_DTYPE , consolidate = consolidate
1813+ )
17981814 blocks .extend (datetime_blocks )
17991815
18001816 if len (items_dict ["DatetimeTZBlock" ]):
@@ -1805,7 +1821,9 @@ def _form_blocks(
18051821 blocks .extend (dttz_blocks )
18061822
18071823 if len (items_dict ["ObjectBlock" ]) > 0 :
1808- object_blocks = _simple_blockify (items_dict ["ObjectBlock" ], np .object_ )
1824+ object_blocks = _simple_blockify (
1825+ items_dict ["ObjectBlock" ], np .object_ , consolidate = consolidate
1826+ )
18091827 blocks .extend (object_blocks )
18101828
18111829 if len (items_dict ["CategoricalBlock" ]) > 0 :
@@ -1844,11 +1862,14 @@ def _form_blocks(
18441862 return blocks
18451863
18461864
1847- def _simple_blockify (tuples , dtype ) -> List [Block ]:
1865+ def _simple_blockify (tuples , dtype , consolidate : bool ) -> List [Block ]:
18481866 """
18491867 return a single array of a block that has a single dtype; if dtype is
18501868 not None, coerce to this dtype
18511869 """
1870+ if not consolidate :
1871+ return _tuples_to_blocks_no_consolidate (tuples , dtype = dtype )
1872+
18521873 values , placement = _stack_arrays (tuples , dtype )
18531874
18541875 # TODO: CHECK DTYPE?
@@ -1859,8 +1880,12 @@ def _simple_blockify(tuples, dtype) -> List[Block]:
18591880 return [block ]
18601881
18611882
1862- def _multi_blockify (tuples , dtype : Optional [Dtype ] = None ):
1883+ def _multi_blockify (tuples , dtype : Optional [DtypeObj ] = None , consolidate : bool = True ):
18631884 """ return an array of blocks that potentially have different dtypes """
1885+
1886+ if not consolidate :
1887+ return _tuples_to_blocks_no_consolidate (tuples , dtype = dtype )
1888+
18641889 # group by dtype
18651890 grouper = itertools .groupby (tuples , lambda x : x [1 ].dtype )
18661891
@@ -1880,6 +1905,18 @@ def _multi_blockify(tuples, dtype: Optional[Dtype] = None):
18801905 return new_blocks
18811906
18821907
1908+ def _tuples_to_blocks_no_consolidate (tuples , dtype : Optional [DtypeObj ]) -> List [Block ]:
1909+ # tuples produced within _form_blocks are of the form (placement, whatever, array)
1910+ if dtype is not None :
1911+ return [
1912+ new_block (
1913+ np .atleast_2d (x [1 ].astype (dtype , copy = False )), placement = x [0 ], ndim = 2
1914+ )
1915+ for x in tuples
1916+ ]
1917+ return [new_block (np .atleast_2d (x [1 ]), placement = x [0 ], ndim = 2 ) for x in tuples ]
1918+
1919+
18831920def _stack_arrays (tuples , dtype : np .dtype ):
18841921
18851922 placement , arrays = zip (* tuples )
0 commit comments