@@ -180,14 +180,14 @@ def rec_array_to_mgr(
180
180
# create the manager
181
181
182
182
# error: Argument 1 to "reorder_arrays" has incompatible type "List[ndarray]";
183
- # expected "List[ExtensionArray]"
183
+ # expected "List[Union[ ExtensionArray, ndarray] ]"
184
184
arrays , arr_columns = reorder_arrays (
185
- new_arrays , arr_columns , columns # type: ignore[arg-type]
185
+ new_arrays , arr_columns , columns , len ( index ) # type: ignore[arg-type]
186
186
)
187
187
if columns is None :
188
188
columns = arr_columns
189
189
190
- mgr = arrays_to_mgr (arrays , arr_columns , index , columns , dtype = dtype , typ = typ )
190
+ mgr = arrays_to_mgr (arrays , columns , index , columns , dtype = dtype , typ = typ )
191
191
192
192
if copy :
193
193
mgr = mgr .copy ()
@@ -655,13 +655,33 @@ def _extract_index(data) -> Index:
655
655
656
656
657
657
def reorder_arrays (
658
- arrays : list [ArrayLike ], arr_columns : Index , columns : Index | None
658
+ arrays : list [ArrayLike ], arr_columns : Index , columns : Index | None , length : int
659
659
) -> tuple [list [ArrayLike ], Index ]:
660
+ """
661
+ Pre-emptively (cheaply) reindex arrays with new columns.
662
+ """
660
663
# reorder according to the columns
661
- if columns is not None and len (columns ) and len (arr_columns ):
662
- indexer = ensure_index (arr_columns ).get_indexer (columns )
663
- arr_columns = ensure_index ([arr_columns [i ] for i in indexer ])
664
- arrays = [arrays [i ] for i in indexer ]
664
+ if columns is not None :
665
+ if not columns .equals (arr_columns ):
666
+ # if they are equal, there is nothing to do
667
+ new_arrays : list [ArrayLike | None ]
668
+ new_arrays = [None ] * len (columns )
669
+ indexer = arr_columns .get_indexer (columns )
670
+ for i , k in enumerate (indexer ):
671
+ if k == - 1 :
672
+ # by convention default is all-NaN object dtype
673
+ arr = np .empty (length , dtype = object )
674
+ arr .fill (np .nan )
675
+ else :
676
+ arr = arrays [k ]
677
+ new_arrays [i ] = arr
678
+
679
+ # Incompatible types in assignment (expression has type
680
+ # "List[Union[ExtensionArray, ndarray[Any, Any], None]]", variable
681
+ # has type "List[Union[ExtensionArray, ndarray[Any, Any]]]")
682
+ arrays = new_arrays # type: ignore[assignment]
683
+ arr_columns = columns
684
+
665
685
return arrays , arr_columns
666
686
667
687
0 commit comments