-
-
Notifications
You must be signed in to change notification settings - Fork 18.2k
/
Copy pathmanagers.py
2501 lines (2084 loc) · 82.9 KB
/
managers.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
from collections.abc import (
Callable,
Hashable,
Sequence,
)
import itertools
from typing import (
TYPE_CHECKING,
Any,
Literal,
NoReturn,
cast,
final,
)
import warnings
import numpy as np
from pandas._config.config import get_option
from pandas._libs import (
algos as libalgos,
internals as libinternals,
lib,
)
from pandas._libs.internals import (
BlockPlacement,
BlockValuesRefs,
)
from pandas._libs.tslibs import Timestamp
from pandas.errors import (
AbstractMethodError,
PerformanceWarning,
)
from pandas.util._decorators import cache_readonly
from pandas.util._exceptions import find_stack_level
from pandas.util._validators import validate_bool_kwarg
from pandas.core.dtypes.cast import (
find_common_type,
infer_dtype_from_scalar,
np_can_hold_element,
)
from pandas.core.dtypes.common import (
ensure_platform_int,
is_1d_only_ea_dtype,
is_list_like,
)
from pandas.core.dtypes.dtypes import (
DatetimeTZDtype,
ExtensionDtype,
SparseDtype,
)
from pandas.core.dtypes.generic import (
ABCDataFrame,
ABCSeries,
)
from pandas.core.dtypes.missing import (
array_equals,
isna,
)
import pandas.core.algorithms as algos
from pandas.core.arrays import DatetimeArray
from pandas.core.arrays._mixins import NDArrayBackedExtensionArray
from pandas.core.base import PandasObject
from pandas.core.construction import (
ensure_wrapped_if_datetimelike,
extract_array,
)
from pandas.core.indexers import maybe_convert_indices
from pandas.core.indexes.api import (
Index,
default_index,
ensure_index,
)
from pandas.core.internals.blocks import (
Block,
NumpyBlock,
ensure_block_shape,
extend_blocks,
get_block_type,
maybe_coerce_values,
new_block,
new_block_2d,
)
from pandas.core.internals.ops import (
blockwise_all,
operate_blockwise,
)
if TYPE_CHECKING:
from collections.abc import Generator
from pandas._typing import (
ArrayLike,
AxisInt,
DtypeObj,
QuantileInterpolation,
Self,
Shape,
npt,
)
from pandas.api.extensions import ExtensionArray
def interleaved_dtype(dtypes: list[DtypeObj]) -> DtypeObj | None:
"""
Find the common dtype for `blocks`.
Parameters
----------
blocks : List[DtypeObj]
Returns
-------
dtype : np.dtype, ExtensionDtype, or None
None is returned when `blocks` is empty.
"""
if not len(dtypes):
return None
return find_common_type(dtypes)
def ensure_np_dtype(dtype: DtypeObj) -> np.dtype:
# TODO: https://github.com/pandas-dev/pandas/issues/22791
# Give EAs some input on what happens here. Sparse needs this.
if isinstance(dtype, SparseDtype):
dtype = dtype.subtype
dtype = cast(np.dtype, dtype)
elif isinstance(dtype, ExtensionDtype):
dtype = np.dtype("object")
elif dtype == np.dtype(str):
dtype = np.dtype("object")
return dtype
class BaseBlockManager(PandasObject):
"""
Core internal data structure to implement DataFrame, Series, etc.
Manage a bunch of labeled 2D mixed-type ndarrays. Essentially it's a
lightweight blocked set of labeled data to be manipulated by the DataFrame
public API class
Attributes
----------
shape
ndim
axes
values
items
Methods
-------
set_axis(axis, new_labels)
copy(deep=True)
get_dtypes
apply(func, axes, block_filter_fn)
get_bool_data
get_numeric_data
get_slice(slice_like, axis)
get(label)
iget(loc)
take(indexer, axis)
reindex_axis(new_labels, axis)
reindex_indexer(new_labels, indexer, axis)
delete(label)
insert(loc, label, value)
set(label, value)
Parameters
----------
blocks: Sequence of Block
axes: Sequence of Index
verify_integrity: bool, default True
Notes
-----
This is *not* a public API class
"""
__slots__ = ()
_blknos: npt.NDArray[np.intp]
_blklocs: npt.NDArray[np.intp]
blocks: tuple[Block, ...]
axes: list[Index]
@property
def ndim(self) -> int:
raise NotImplementedError
_known_consolidated: bool
_is_consolidated: bool
def __init__(self, blocks, axes, verify_integrity: bool = True) -> None:
raise NotImplementedError
@final
def __len__(self) -> int:
return len(self.items)
@property
def shape(self) -> Shape:
return tuple(len(ax) for ax in self.axes)
@classmethod
def from_blocks(cls, blocks: list[Block], axes: list[Index]) -> Self:
raise NotImplementedError
@property
def blknos(self) -> npt.NDArray[np.intp]:
"""
Suppose we want to find the array corresponding to our i'th column.
blknos[i] identifies the block from self.blocks that contains this column.
blklocs[i] identifies the column of interest within
self.blocks[self.blknos[i]]
"""
if self._blknos is None:
# Note: these can be altered by other BlockManager methods.
self._rebuild_blknos_and_blklocs()
return self._blknos
@property
def blklocs(self) -> npt.NDArray[np.intp]:
"""
See blknos.__doc__
"""
if self._blklocs is None:
# Note: these can be altered by other BlockManager methods.
self._rebuild_blknos_and_blklocs()
return self._blklocs
def make_empty(self, axes=None) -> Self:
"""return an empty BlockManager with the items axis of len 0"""
if axes is None:
axes = [default_index(0)] + self.axes[1:]
# preserve dtype if possible
if self.ndim == 1:
assert isinstance(self, SingleBlockManager) # for mypy
blk = self.blocks[0]
arr = blk.values[:0]
bp = BlockPlacement(slice(0, 0))
nb = blk.make_block_same_class(arr, placement=bp)
blocks = [nb]
else:
blocks = []
return type(self).from_blocks(blocks, axes)
def __bool__(self) -> bool:
return True
def set_axis(self, axis: AxisInt, new_labels: Index) -> None:
# Caller is responsible for ensuring we have an Index object.
self._validate_set_axis(axis, new_labels)
self.axes[axis] = new_labels
@final
def _validate_set_axis(self, axis: AxisInt, new_labels: Index) -> None:
# Caller is responsible for ensuring we have an Index object.
old_len = len(self.axes[axis])
new_len = len(new_labels)
if axis == 1 and len(self.items) == 0:
# If we are setting the index on a DataFrame with no columns,
# it is OK to change the length.
pass
elif new_len != old_len:
raise ValueError(
f"Length mismatch: Expected axis has {old_len} elements, new "
f"values have {new_len} elements"
)
@property
def is_single_block(self) -> bool:
# Assumes we are 2D; overridden by SingleBlockManager
return len(self.blocks) == 1
@property
def items(self) -> Index:
return self.axes[0]
def _has_no_reference(self, i: int) -> bool:
"""
Check for column `i` if it has references.
(whether it references another array or is itself being referenced)
Returns True if the column has no references.
"""
blkno = self.blknos[i]
return self._has_no_reference_block(blkno)
def _has_no_reference_block(self, blkno: int) -> bool:
"""
Check for block `i` if it has references.
(whether it references another array or is itself being referenced)
Returns True if the block has no references.
"""
return not self.blocks[blkno].refs.has_reference()
def add_references(self, mgr: BaseBlockManager) -> None:
"""
Adds the references from one manager to another. We assume that both
managers have the same block structure.
"""
if len(self.blocks) != len(mgr.blocks):
# If block structure changes, then we made a copy
return
for i, blk in enumerate(self.blocks):
blk.refs = mgr.blocks[i].refs
blk.refs.add_reference(blk)
def references_same_values(self, mgr: BaseBlockManager, blkno: int) -> bool:
"""
Checks if two blocks from two different block managers reference the
same underlying values.
"""
blk = self.blocks[blkno]
return any(blk is ref() for ref in mgr.blocks[blkno].refs.referenced_blocks)
def get_dtypes(self) -> npt.NDArray[np.object_]:
dtypes = np.array([blk.dtype for blk in self.blocks], dtype=object)
return dtypes.take(self.blknos)
@property
def arrays(self) -> list[ArrayLike]:
"""
Quick access to the backing arrays of the Blocks.
Only for compatibility with ArrayManager for testing convenience.
Not to be used in actual code, and return value is not the same as the
ArrayManager method (list of 1D arrays vs iterator of 2D ndarrays / 1D EAs).
Warning! The returned arrays don't handle Copy-on-Write, so this should
be used with caution (only in read-mode).
"""
# TODO: Deprecate, usage in Dask
# https://github.com/dask/dask/blob/484fc3f1136827308db133cd256ba74df7a38d8c/dask/base.py#L1312
return [blk.values for blk in self.blocks]
def __repr__(self) -> str:
output = type(self).__name__
for i, ax in enumerate(self.axes):
if i == 0:
output += f"\nItems: {ax}"
else:
output += f"\nAxis {i}: {ax}"
for block in self.blocks:
output += f"\n{block}"
return output
def _equal_values(self, other: Self) -> bool:
"""
To be implemented by the subclasses. Only check the column values
assuming shape and indexes have already been checked.
"""
raise AbstractMethodError(self)
@final
def equals(self, other: object) -> bool:
"""
Implementation for DataFrame.equals
"""
if not isinstance(other, type(self)):
return False
self_axes, other_axes = self.axes, other.axes
if len(self_axes) != len(other_axes):
return False
if not all(ax1.equals(ax2) for ax1, ax2 in zip(self_axes, other_axes)):
return False
return self._equal_values(other)
def apply(
self,
f,
align_keys: list[str] | None = None,
**kwargs,
) -> Self:
"""
Iterate over the blocks, collect and create a new BlockManager.
Parameters
----------
f : str or callable
Name of the Block method to apply.
align_keys: List[str] or None, default None
**kwargs
Keywords to pass to `f`
Returns
-------
BlockManager
"""
assert "filter" not in kwargs
align_keys = align_keys or []
result_blocks: list[Block] = []
# fillna: Series/DataFrame is responsible for making sure value is aligned
aligned_args = {k: kwargs[k] for k in align_keys}
for b in self.blocks:
if aligned_args:
for k, obj in aligned_args.items():
if isinstance(obj, (ABCSeries, ABCDataFrame)):
# The caller is responsible for ensuring that
# obj.axes[-1].equals(self.items)
if obj.ndim == 1:
kwargs[k] = obj.iloc[b.mgr_locs.indexer]._values
else:
kwargs[k] = obj.iloc[:, b.mgr_locs.indexer]._values
else:
# otherwise we have an ndarray
kwargs[k] = obj[b.mgr_locs.indexer]
if callable(f):
applied = b.apply(f, **kwargs)
else:
applied = getattr(b, f)(**kwargs)
result_blocks = extend_blocks(applied, result_blocks)
out = type(self).from_blocks(result_blocks, self.axes)
return out
@final
def isna(self, func) -> Self:
return self.apply("apply", func=func)
@final
def fillna(self, value, limit: int | None, inplace: bool) -> Self:
if limit is not None:
# Do this validation even if we go through one of the no-op paths
limit = libalgos.validate_limit(None, limit=limit)
return self.apply(
"fillna",
value=value,
limit=limit,
inplace=inplace,
)
@final
def where(self, other, cond, align: bool) -> Self:
if align:
align_keys = ["other", "cond"]
else:
align_keys = ["cond"]
other = extract_array(other, extract_numpy=True)
return self.apply(
"where",
align_keys=align_keys,
other=other,
cond=cond,
)
@final
def putmask(self, mask, new, align: bool = True) -> Self:
if align:
align_keys = ["new", "mask"]
else:
align_keys = ["mask"]
new = extract_array(new, extract_numpy=True)
return self.apply(
"putmask",
align_keys=align_keys,
mask=mask,
new=new,
)
@final
def round(self, decimals: int) -> Self:
return self.apply("round", decimals=decimals)
@final
def replace(self, to_replace, value, inplace: bool) -> Self:
inplace = validate_bool_kwarg(inplace, "inplace")
# NDFrame.replace ensures the not-is_list_likes here
assert not lib.is_list_like(to_replace)
assert not lib.is_list_like(value)
return self.apply(
"replace",
to_replace=to_replace,
value=value,
inplace=inplace,
)
@final
def replace_regex(self, **kwargs) -> Self:
return self.apply("_replace_regex", **kwargs)
@final
def replace_list(
self,
src_list: list[Any],
dest_list: list[Any],
inplace: bool = False,
regex: bool = False,
) -> Self:
"""do a list replace"""
inplace = validate_bool_kwarg(inplace, "inplace")
bm = self.apply(
"replace_list",
src_list=src_list,
dest_list=dest_list,
inplace=inplace,
regex=regex,
)
bm._consolidate_inplace()
return bm
def interpolate(self, inplace: bool, **kwargs) -> Self:
return self.apply("interpolate", inplace=inplace, **kwargs)
def pad_or_backfill(self, inplace: bool, **kwargs) -> Self:
return self.apply("pad_or_backfill", inplace=inplace, **kwargs)
def shift(self, periods: int, fill_value) -> Self:
if fill_value is lib.no_default:
fill_value = None
return self.apply("shift", periods=periods, fill_value=fill_value)
def setitem(self, indexer, value) -> Self:
"""
Set values with indexer.
For SingleBlockManager, this backs s[indexer] = value
"""
if isinstance(indexer, np.ndarray) and indexer.ndim > self.ndim:
raise ValueError(f"Cannot set values with ndim > {self.ndim}")
if not self._has_no_reference(0):
# this method is only called if there is a single block -> hardcoded 0
# Split blocks to only copy the columns we want to modify
if self.ndim == 2 and isinstance(indexer, tuple):
blk_loc = self.blklocs[indexer[1]]
if is_list_like(blk_loc) and blk_loc.ndim == 2:
blk_loc = np.squeeze(blk_loc, axis=0)
elif not is_list_like(blk_loc):
# Keep dimension and copy data later
blk_loc = [blk_loc] # type: ignore[assignment]
if len(blk_loc) == 0:
return self.copy(deep=False)
values = self.blocks[0].values
if values.ndim == 2:
values = values[blk_loc]
# "T" has no attribute "_iset_split_block"
self._iset_split_block( # type: ignore[attr-defined]
0, blk_loc, values
)
# first block equals values
self.blocks[0].setitem((indexer[0], np.arange(len(blk_loc))), value)
return self
# No need to split if we either set all columns or on a single block
# manager
self = self.copy()
return self.apply("setitem", indexer=indexer, value=value)
def diff(self, n: int) -> Self:
# only reached with self.ndim == 2
return self.apply("diff", n=n)
def astype(self, dtype, errors: str = "raise") -> Self:
return self.apply("astype", dtype=dtype, errors=errors)
def convert(self) -> Self:
return self.apply("convert")
def convert_dtypes(self, **kwargs):
return self.apply("convert_dtypes", **kwargs)
def get_values_for_csv(
self, *, float_format, date_format, decimal, na_rep: str = "nan", quoting=None
) -> Self:
"""
Convert values to native types (strings / python objects) that are used
in formatting (repr / csv).
"""
return self.apply(
"get_values_for_csv",
na_rep=na_rep,
quoting=quoting,
float_format=float_format,
date_format=date_format,
decimal=decimal,
)
@property
def any_extension_types(self) -> bool:
"""Whether any of the blocks in this manager are extension blocks"""
return any(block.is_extension for block in self.blocks)
@property
def is_view(self) -> bool:
"""return a boolean if we are a single block and are a view"""
if len(self.blocks) == 1:
return self.blocks[0].is_view
# It is technically possible to figure out which blocks are views
# e.g. [ b.values.base is not None for b in self.blocks ]
# but then we have the case of possibly some blocks being a view
# and some blocks not. setting in theory is possible on the non-view
# blocks. But this is a bit
# complicated
return False
def _get_data_subset(self, predicate: Callable) -> Self:
blocks = [blk for blk in self.blocks if predicate(blk.values)]
return self._combine(blocks)
def get_bool_data(self) -> Self:
"""
Select blocks that are bool-dtype and columns from object-dtype blocks
that are all-bool.
"""
new_blocks = []
for blk in self.blocks:
if blk.dtype == bool:
new_blocks.append(blk)
elif blk.is_object:
new_blocks.extend(nb for nb in blk._split() if nb.is_bool)
return self._combine(new_blocks)
def get_numeric_data(self) -> Self:
numeric_blocks = [blk for blk in self.blocks if blk.is_numeric]
if len(numeric_blocks) == len(self.blocks):
# Avoid somewhat expensive _combine
return self
return self._combine(numeric_blocks)
def _combine(self, blocks: list[Block], index: Index | None = None) -> Self:
"""return a new manager with the blocks"""
if len(blocks) == 0:
if self.ndim == 2:
# retain our own Index dtype
if index is not None:
axes = [self.items[:0], index]
else:
axes = [self.items[:0]] + self.axes[1:]
return self.make_empty(axes)
return self.make_empty()
# FIXME: optimization potential
indexer = np.sort(np.concatenate([b.mgr_locs.as_array for b in blocks]))
inv_indexer = lib.get_reverse_indexer(indexer, self.shape[0])
new_blocks: list[Block] = []
for b in blocks:
nb = b.copy(deep=False)
nb.mgr_locs = BlockPlacement(inv_indexer[nb.mgr_locs.indexer])
new_blocks.append(nb)
axes = list(self.axes)
if index is not None:
axes[-1] = index
axes[0] = self.items.take(indexer)
return type(self).from_blocks(new_blocks, axes)
@property
def nblocks(self) -> int:
return len(self.blocks)
def copy(self, deep: bool | Literal["all"] = True) -> Self:
"""
Make deep or shallow copy of BlockManager
Parameters
----------
deep : bool, string or None, default True
If False or None, return a shallow copy (do not copy data)
If 'all', copy data and a deep copy of the index
Returns
-------
BlockManager
"""
# this preserves the notion of view copying of axes
if deep:
# hit in e.g. tests.io.json.test_pandas
def copy_func(ax):
return ax.copy(deep=True) if deep == "all" else ax.view()
new_axes = [copy_func(ax) for ax in self.axes]
else:
new_axes = [ax.view() for ax in self.axes]
res = self.apply("copy", deep=deep)
res.axes = new_axes
if self.ndim > 1:
# Avoid needing to re-compute these
blknos = self._blknos
if blknos is not None:
res._blknos = blknos.copy()
res._blklocs = self._blklocs.copy()
if deep:
res._consolidate_inplace()
return res
def is_consolidated(self) -> bool:
return True
def consolidate(self) -> Self:
"""
Join together blocks having same dtype
Returns
-------
y : BlockManager
"""
if self.is_consolidated():
return self
bm = type(self)(self.blocks, self.axes, verify_integrity=False)
bm._is_consolidated = False
bm._consolidate_inplace()
return bm
def _consolidate_inplace(self) -> None:
return
@final
def reindex_axis(
self,
new_index: Index,
axis: AxisInt,
fill_value=None,
only_slice: bool = False,
) -> Self:
"""
Conform data manager to new index.
"""
new_index, indexer = self.axes[axis].reindex(new_index)
return self.reindex_indexer(
new_index,
indexer,
axis=axis,
fill_value=fill_value,
only_slice=only_slice,
)
def reindex_indexer(
self,
new_axis: Index,
indexer: npt.NDArray[np.intp] | None,
axis: AxisInt,
fill_value=None,
allow_dups: bool = False,
only_slice: bool = False,
*,
use_na_proxy: bool = False,
) -> Self:
"""
Parameters
----------
new_axis : Index
indexer : ndarray[intp] or None
axis : int
fill_value : object, default None
allow_dups : bool, default False
only_slice : bool, default False
Whether to take views, not copies, along columns.
use_na_proxy : bool, default False
Whether to use a np.void ndarray for newly introduced columns.
pandas-indexer with -1's only.
"""
if indexer is None:
if new_axis is self.axes[axis]:
return self
result = self.copy(deep=False)
result.axes = list(self.axes)
result.axes[axis] = new_axis
return result
# Should be intp, but in some cases we get int64 on 32bit builds
assert isinstance(indexer, np.ndarray)
# some axes don't allow reindexing with dups
if not allow_dups:
self.axes[axis]._validate_can_reindex(indexer)
if axis >= self.ndim:
raise IndexError("Requested axis not found in manager")
if axis == 0:
new_blocks = list(
self._slice_take_blocks_ax0(
indexer,
fill_value=fill_value,
only_slice=only_slice,
use_na_proxy=use_na_proxy,
)
)
else:
new_blocks = [
blk.take_nd(
indexer,
axis=1,
fill_value=(
fill_value if fill_value is not None else blk.fill_value
),
)
for blk in self.blocks
]
new_axes = list(self.axes)
new_axes[axis] = new_axis
new_mgr = type(self).from_blocks(new_blocks, new_axes)
if axis == 1:
# We can avoid the need to rebuild these
new_mgr._blknos = self.blknos.copy()
new_mgr._blklocs = self.blklocs.copy()
return new_mgr
def _slice_take_blocks_ax0(
self,
slice_or_indexer: slice | np.ndarray,
fill_value=lib.no_default,
only_slice: bool = False,
*,
use_na_proxy: bool = False,
ref_inplace_op: bool = False,
) -> Generator[Block, None, None]:
"""
Slice/take blocks along axis=0.
Overloaded for SingleBlock
Parameters
----------
slice_or_indexer : slice or np.ndarray[int64]
fill_value : scalar, default lib.no_default
only_slice : bool, default False
If True, we always return views on existing arrays, never copies.
This is used when called from ops.blockwise.operate_blockwise.
use_na_proxy : bool, default False
Whether to use a np.void ndarray for newly introduced columns.
ref_inplace_op: bool, default False
Don't track refs if True because we operate inplace
Yields
------
Block : New Block
"""
allow_fill = fill_value is not lib.no_default
sl_type, slobj, sllen = _preprocess_slice_or_indexer(
slice_or_indexer, self.shape[0], allow_fill=allow_fill
)
if self.is_single_block:
blk = self.blocks[0]
if sl_type == "slice":
# GH#32959 EABlock would fail since we can't make 0-width
# TODO(EA2D): special casing unnecessary with 2D EAs
if sllen == 0:
return
bp = BlockPlacement(slice(0, sllen))
yield blk.getitem_block_columns(slobj, new_mgr_locs=bp)
return
elif not allow_fill or self.ndim == 1:
if allow_fill and fill_value is None:
fill_value = blk.fill_value
if not allow_fill and only_slice:
# GH#33597 slice instead of take, so we get
# views instead of copies
for i, ml in enumerate(slobj):
yield blk.getitem_block_columns(
slice(ml, ml + 1),
new_mgr_locs=BlockPlacement(i),
ref_inplace_op=ref_inplace_op,
)
else:
bp = BlockPlacement(slice(0, sllen))
yield blk.take_nd(
slobj,
axis=0,
new_mgr_locs=bp,
fill_value=fill_value,
)
return
if sl_type == "slice":
blknos = self.blknos[slobj]
blklocs = self.blklocs[slobj]
else:
blknos = algos.take_nd(
self.blknos, slobj, fill_value=-1, allow_fill=allow_fill
)
blklocs = algos.take_nd(
self.blklocs, slobj, fill_value=-1, allow_fill=allow_fill
)
# When filling blknos, make sure blknos is updated before appending to
# blocks list, that way new blkno is exactly len(blocks).
group = not only_slice
for blkno, mgr_locs in libinternals.get_blkno_placements(blknos, group=group):
if blkno == -1:
# If we've got here, fill_value was not lib.no_default
yield self._make_na_block(
placement=mgr_locs,
fill_value=fill_value,
use_na_proxy=use_na_proxy,
)
else:
blk = self.blocks[blkno]
# Otherwise, slicing along items axis is necessary.
if not blk._can_consolidate and not blk._validate_ndim:
# i.e. we dont go through here for DatetimeTZBlock
# A non-consolidatable block, it's easy, because there's
# only one item and each mgr loc is a copy of that single
# item.
deep = False
for mgr_loc in mgr_locs:
newblk = blk.copy(deep=deep)
newblk.mgr_locs = BlockPlacement(slice(mgr_loc, mgr_loc + 1))
yield newblk
else:
# GH#32779 to avoid the performance penalty of copying,
# we may try to only slice
taker = blklocs[mgr_locs.indexer]
max_len = max(len(mgr_locs), taker.max() + 1)
taker = lib.maybe_indices_to_slice(taker, max_len)
if isinstance(taker, slice):
nb = blk.getitem_block_columns(taker, new_mgr_locs=mgr_locs)
yield nb
elif only_slice:
# GH#33597 slice instead of take, so we get
# views instead of copies
for i, ml in zip(taker, mgr_locs):
slc = slice(i, i + 1)
bp = BlockPlacement(ml)
nb = blk.getitem_block_columns(slc, new_mgr_locs=bp)
# We have np.shares_memory(nb.values, blk.values)
yield nb
else:
nb = blk.take_nd(taker, axis=0, new_mgr_locs=mgr_locs)
yield nb
def _make_na_block(
self, placement: BlockPlacement, fill_value=None, use_na_proxy: bool = False
) -> Block:
# Note: we only get here with self.ndim == 2
if use_na_proxy:
assert fill_value is None
shape = (len(placement), self.shape[1])
vals = np.empty(shape, dtype=np.void)
nb = NumpyBlock(vals, placement, ndim=2)
return nb
if fill_value is None or fill_value is np.nan:
fill_value = np.nan
# GH45857 avoid unnecessary upcasting
dtype = interleaved_dtype([blk.dtype for blk in self.blocks])
if dtype is not None and np.issubdtype(dtype.type, np.floating):
fill_value = dtype.type(fill_value)