forked from modin-project/modin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dataframe.py
4546 lines (4105 loc) · 172 KB
/
dataframe.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
# Licensed to Modin Development Team under one or more contributor license agreements.
# See the NOTICE file distributed with this work for additional information regarding
# copyright ownership. The Modin Development Team licenses this file to you under the
# Apache License, Version 2.0 (the "License"); you may not use this file except in
# compliance with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distributed under
# the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific language
# governing permissions and limitations under the License.
"""
Module contains class PandasDataframe.
PandasDataframe is a parent abstract class for any dataframe class
for pandas storage format.
"""
import datetime
import re
from typing import TYPE_CHECKING, Callable, Dict, Hashable, List, Optional, Union
import numpy as np
import pandas
from pandas._libs.lib import no_default
from pandas.api.types import is_object_dtype
from pandas.core.dtypes.common import is_dtype_equal, is_list_like, is_numeric_dtype
from pandas.core.indexes.api import Index, RangeIndex
from modin.config import IsRayCluster, NPartitions
from modin.core.dataframe.base.dataframe.dataframe import ModinDataframe
from modin.core.dataframe.base.dataframe.utils import Axis, JoinType
from modin.core.dataframe.pandas.dataframe.utils import (
ShuffleSortFunctions,
add_missing_categories_to_groupby,
lazy_metadata_decorator,
)
from modin.core.dataframe.pandas.metadata import (
DtypesDescriptor,
LazyProxyCategoricalDtype,
ModinDtypes,
ModinIndex,
)
from modin.core.storage_formats.pandas.parsers import (
find_common_type_cat as find_common_type,
)
from modin.core.storage_formats.pandas.query_compiler import PandasQueryCompiler
from modin.core.storage_formats.pandas.utils import get_length_list
from modin.error_message import ErrorMessage
if TYPE_CHECKING:
from modin.core.dataframe.base.interchange.dataframe_protocol.dataframe import (
ProtocolDataframe,
)
from pandas._typing import npt
from modin.logging import ClassLogger
from modin.pandas.indexing import is_range_like
from modin.pandas.utils import check_both_not_none, is_full_grab_slice
from modin.utils import MODIN_UNNAMED_SERIES_LABEL
class PandasDataframe(ClassLogger):
"""
An abstract class that represents the parent class for any pandas storage format dataframe class.
This class provides interfaces to run operations on dataframe partitions.
Parameters
----------
partitions : np.ndarray
A 2D NumPy array of partitions.
index : sequence or callable, optional
The index for the dataframe. Converted to a ``pandas.Index``.
Is computed from partitions on demand if not specified.
If ``callable() -> (pandas.Index, list of row lengths or None)`` type,
then the calculation will be delayed until `self.index` is called.
columns : sequence, optional
The columns object for the dataframe. Converted to a ``pandas.Index``.
Is computed from partitions on demand if not specified.
row_lengths : list, optional
The length of each partition in the rows. The "height" of
each of the block partitions. Is computed if not provided.
column_widths : list, optional
The width of each partition in the columns. The "width" of
each of the block partitions. Is computed if not provided.
dtypes : pandas.Series or callable, optional
The data types for the dataframe columns.
"""
_partition_mgr_cls = None
_query_compiler_cls = PandasQueryCompiler
# These properties flag whether or not we are deferring the metadata synchronization
_deferred_index = False
_deferred_column = False
@pandas.util.cache_readonly
def __constructor__(self):
"""
Create a new instance of this object.
Returns
-------
PandasDataframe
"""
return type(self)
def __init__(
self,
partitions,
index=None,
columns=None,
row_lengths=None,
column_widths=None,
dtypes=None,
):
self._partitions = partitions
self.set_index_cache(index)
self.set_columns_cache(columns)
self._row_lengths_cache = row_lengths
self._column_widths_cache = column_widths
self.set_dtypes_cache(dtypes)
self._validate_axes_lengths()
self._filter_empties(compute_metadata=False)
def _validate_axes_lengths(self):
"""Validate that labels are split correctly if split is known."""
if (
self._row_lengths_cache is not None
and self.has_materialized_index
and len(self.index) > 0
):
# An empty frame can have 0 rows but a nonempty index. If the frame
# does have rows, the number of rows must equal the size of the
# index.
num_rows = sum(self._row_lengths_cache)
if num_rows > 0:
ErrorMessage.catch_bugs_and_request_email(
num_rows != len(self.index),
f"Row lengths: {num_rows} != {len(self.index)}",
)
ErrorMessage.catch_bugs_and_request_email(
any(val < 0 for val in self._row_lengths_cache),
f"Row lengths cannot be negative: {self._row_lengths_cache}",
)
if (
self._column_widths_cache is not None
and self.has_materialized_columns
and len(self.columns) > 0
):
# An empty frame can have 0 column but a nonempty column index. If
# the frame does have columns, the number of columns must equal the
# size of the columns.
num_columns = sum(self._column_widths_cache)
if num_columns > 0:
ErrorMessage.catch_bugs_and_request_email(
num_columns != len(self.columns),
f"Column widths: {num_columns} != {len(self.columns)}",
)
ErrorMessage.catch_bugs_and_request_email(
any(val < 0 for val in self._column_widths_cache),
f"Column widths cannot be negative: {self._column_widths_cache}",
)
@property
def num_parts(self) -> int:
"""
Get the total number of partitions for this frame.
Returns
-------
int
"""
return np.prod(self._partitions.shape)
@property
def row_lengths(self):
"""
Compute the row partitions lengths if they are not cached.
Returns
-------
list
A list of row partitions lengths.
"""
if self._row_lengths_cache is None:
if len(self._partitions.T) > 0:
row_parts = self._partitions.T[0]
self._row_lengths_cache = self._get_lengths(row_parts, Axis.ROW_WISE)
else:
self._row_lengths_cache = []
return self._row_lengths_cache
@classmethod
def _get_lengths(cls, parts, axis):
"""
Get list of dimensions for all the provided parts.
Parameters
----------
parts : list
List of parttions.
axis : {0, 1}
The axis along which to get the lengths (0 - length across rows or, 1 - width across columns).
Returns
-------
list
"""
if axis == Axis.ROW_WISE:
return [part.length() for part in parts]
else:
return [part.width() for part in parts]
def __len__(self) -> int:
"""
Return length of index axis.
Returns
-------
int
"""
if self.has_materialized_index:
_len = len(self.index)
else:
_len = sum(self.row_lengths)
return _len
@property
def column_widths(self):
"""
Compute the column partitions widths if they are not cached.
Returns
-------
list
A list of column partitions widths.
"""
if self._column_widths_cache is None:
if len(self._partitions) > 0:
col_parts = self._partitions[0]
self._column_widths_cache = self._get_lengths(col_parts, Axis.COL_WISE)
else:
self._column_widths_cache = []
return self._column_widths_cache
def _set_axis_lengths_cache(self, value, axis=0):
"""
Set the row/column lengths cache for the specified axis.
Parameters
----------
value : list of ints
axis : int, default: 0
0 for row lengths and 1 for column widths.
"""
if axis == 0:
self._row_lengths_cache = value
else:
self._column_widths_cache = value
def _get_axis_lengths_cache(self, axis=0):
"""
Get partition's shape caches along the specified axis if avaliable.
Parameters
----------
axis : int, default: 0
0 - get row lengths cache, 1 - get column widths cache.
Returns
-------
list of ints or None
If the cache is computed return a list of ints, ``None`` otherwise.
"""
return self._row_lengths_cache if axis == 0 else self._column_widths_cache
def _get_axis_lengths(self, axis: int = 0) -> List[int]:
"""
Get row lengths/column widths.
Parameters
----------
axis : int, default: 0
Returns
-------
list of ints
"""
return self.row_lengths if axis == 0 else self.column_widths
@property
def has_dtypes_cache(self):
"""
Check if the dtypes cache exists.
Returns
-------
bool
"""
return self._dtypes is not None
@property
def has_materialized_dtypes(self):
"""
Check if dataframe has materialized index cache.
Returns
-------
bool
"""
return self.has_dtypes_cache and self._dtypes.is_materialized
def copy_dtypes_cache(self):
"""
Copy the dtypes cache.
Returns
-------
pandas.Series, callable or None
If there is an pandas.Series in the cache, then copying occurs.
"""
dtypes_cache = None
if self.has_dtypes_cache:
dtypes_cache = self._dtypes.copy()
return dtypes_cache
def _maybe_update_proxies(self, dtypes, new_parent=None):
"""
Update lazy proxies stored inside of `dtypes` with a new parent inplace.
Parameters
----------
dtypes : pandas.Series, ModinDtypes or callable
new_parent : object, optional
A new parent to link the proxies to. If not specified
will consider the `self` to be a new parent.
Returns
-------
pandas.Series, ModinDtypes or callable
"""
new_parent = new_parent or self
if isinstance(dtypes, ModinDtypes):
dtypes = dtypes.maybe_specify_new_frame_ref(new_parent)
if isinstance(dtypes, pandas.Series):
LazyProxyCategoricalDtype.update_dtypes(dtypes, new_parent)
return dtypes
def set_dtypes_cache(self, dtypes):
"""
Set dtypes cache.
Parameters
----------
dtypes : pandas.Series, ModinDtypes, callable or None
"""
dtypes = self._maybe_update_proxies(dtypes)
if dtypes is None and self.has_materialized_columns:
# try to set a descriptor instead of 'None' to be more flexible in
# dtypes computing
try:
self._dtypes = ModinDtypes(
DtypesDescriptor(
cols_with_unknown_dtypes=self.columns.tolist(), parent_df=self
)
)
except NotImplementedError:
self._dtypes = None
elif isinstance(dtypes, ModinDtypes) or dtypes is None:
self._dtypes = dtypes
else:
self._dtypes = ModinDtypes(dtypes)
@property
def dtypes(self):
"""
Compute the data types if they are not cached.
Returns
-------
pandas.Series
A pandas Series containing the data types for this dataframe.
"""
if self.has_dtypes_cache:
dtypes = self._dtypes.get()
else:
dtypes = self._compute_dtypes()
self.set_dtypes_cache(dtypes)
return dtypes
def get_dtypes_set(self):
"""
Get a set of dtypes that are in this dataframe.
Returns
-------
set
"""
if isinstance(self._dtypes, ModinDtypes):
return self._dtypes.get_dtypes_set()
return set(self.dtypes.values)
def _compute_dtypes(self, columns=None):
"""
Compute the data types via TreeReduce pattern for the specified columns.
Parameters
----------
columns : list-like, default: None
Columns to compute dtypes for. If not specified compute dtypes
for all the columns in the dataframe.
Returns
-------
pandas.Series
A pandas Series containing the data types for this dataframe.
"""
def dtype_builder(df):
return df.apply(lambda col: find_common_type(col.values), axis=0)
if columns is not None:
# Sorting positions to request columns in the order they're stored (it's more efficient)
numeric_indices = sorted(self.columns.get_indexer_for(columns))
if any(pos < 0 for pos in numeric_indices):
raise KeyError(
f"Some of the columns are not in index: subset={columns}; columns={self.columns}"
)
obj = self.take_2d_labels_or_positional(
col_labels=self.columns[numeric_indices].tolist()
)
else:
obj = self
# For now we will use a pandas Series for the dtypes.
if len(obj.columns) > 0:
dtypes = (
obj.tree_reduce(0, lambda df: df.dtypes, dtype_builder)
.to_pandas()
.iloc[0]
)
else:
dtypes = pandas.Series([])
# reset name to None because we use MODIN_UNNAMED_SERIES_LABEL internally
dtypes.name = None
return dtypes
_index_cache = None
_columns_cache = None
def set_index_cache(self, index):
"""
Set index cache.
Parameters
----------
index : sequence, callable or None
"""
if index is None:
self._index_cache = ModinIndex(self, axis=0)
elif isinstance(index, ModinIndex):
# update reference with the new frame to not pollute memory
self._index_cache = index.maybe_specify_new_frame_ref(self, axis=0)
else:
self._index_cache = ModinIndex(index)
def set_columns_cache(self, columns):
"""
Set columns cache.
Parameters
----------
columns : sequence, callable or None
"""
if columns is None:
self._columns_cache = ModinIndex(self, axis=1)
elif isinstance(columns, ModinIndex):
# update reference with the new frame to not pollute memory
self._columns_cache = columns.maybe_specify_new_frame_ref(self, axis=1)
else:
self._columns_cache = ModinIndex(columns)
def set_axis_cache(self, value, axis=0):
"""
Set cache for the specified axis (index or columns).
Parameters
----------
value : sequence, callable or None
axis : int, default: 0
"""
if axis == 0:
self.set_index_cache(value)
else:
self.set_columns_cache(value)
def has_axis_cache(self, axis=0) -> bool:
"""
Check if the cache for the specified axis exists.
Parameters
----------
axis : int, default: 0
Returns
-------
bool
"""
return self.has_index_cache if axis == 0 else self.has_columns_cache
@property
def has_index_cache(self):
"""
Check if the index cache exists.
Returns
-------
bool
"""
return self._index_cache is not None
def copy_index_cache(self, copy_lengths=False):
"""
Copy the index cache.
Parameters
----------
copy_lengths : bool, default: False
Whether to copy the stored partition lengths to the
new index object.
Returns
-------
pandas.Index, callable or ModinIndex
If there is an pandas.Index in the cache, then copying occurs.
"""
idx_cache = self._index_cache
if self.has_index_cache:
idx_cache = self._index_cache.copy(copy_lengths)
return idx_cache
def _get_axis_cache(self, axis=0) -> ModinIndex:
"""
Get axis cache for the specified axis if available.
Parameters
----------
axis : int, default: 0
Returns
-------
ModinIndex
"""
return self._index_cache if axis == 0 else self._columns_cache
@property
def has_columns_cache(self):
"""
Check if the columns cache exists.
Returns
-------
bool
"""
return self._columns_cache is not None
def copy_columns_cache(self, copy_lengths=False):
"""
Copy the columns cache.
Parameters
----------
copy_lengths : bool, default: False
Whether to copy the stored partition lengths to the
new index object.
Returns
-------
pandas.Index or None
If there is an pandas.Index in the cache, then copying occurs.
"""
columns_cache = self._columns_cache
if columns_cache is not None:
columns_cache = columns_cache.copy(copy_lengths)
return columns_cache
def copy_axis_cache(self, axis=0, copy_lengths=False):
"""
Copy the axis cache (index or columns).
Parameters
----------
axis : int, default: 0
copy_lengths : bool, default: False
Whether to copy the stored partition lengths to the
new index object.
Returns
-------
pandas.Index, callable or None
If there is an pandas.Index in the cache, then copying occurs.
"""
if axis == 0:
return self.copy_index_cache(copy_lengths)
else:
return self.copy_columns_cache(copy_lengths)
@property
def has_materialized_index(self):
"""
Check if dataframe has materialized index cache.
Returns
-------
bool
"""
return self.has_index_cache and self._index_cache.is_materialized
@property
def has_materialized_columns(self):
"""
Check if dataframe has materialized columns cache.
Returns
-------
bool
"""
return self.has_columns_cache and self._columns_cache.is_materialized
def _validate_set_axis(self, new_labels, old_labels):
"""
Validate the possibility of replacement of old labels with the new labels.
Parameters
----------
new_labels : list-like
The labels to replace with.
old_labels : list-like
The labels to replace.
Returns
-------
list-like
The validated labels.
"""
new_labels = (
ModinIndex(new_labels)
if not isinstance(new_labels, ModinIndex)
else new_labels
)
old_len = len(old_labels)
new_len = len(new_labels)
if old_len != new_len:
raise ValueError(
f"Length mismatch: Expected axis has {old_len} elements, "
+ f"new values have {new_len} elements"
)
return new_labels
def _get_index(self):
"""
Get the index from the cache object.
Returns
-------
pandas.Index
An index object containing the row labels.
"""
if self.has_index_cache:
index, row_lengths = self._index_cache.get(return_lengths=True)
else:
index, row_lengths = self._compute_axis_labels_and_lengths(0)
self.set_index_cache(index)
if self._row_lengths_cache is None:
self._row_lengths_cache = row_lengths
return index
def _get_columns(self):
"""
Get the columns from the cache object.
Returns
-------
pandas.Index
An index object containing the column labels.
"""
if self.has_columns_cache:
columns, column_widths = self._columns_cache.get(return_lengths=True)
else:
columns, column_widths = self._compute_axis_labels_and_lengths(1)
self.set_columns_cache(columns)
if self._column_widths_cache is None:
self._column_widths_cache = column_widths
return columns
def _set_index(self, new_index):
"""
Replace the current row labels with new labels.
Parameters
----------
new_index : list-like
The new row labels.
"""
if self.has_materialized_index:
new_index = self._validate_set_axis(new_index, self._index_cache)
self.set_index_cache(new_index)
self.synchronize_labels(axis=0)
def _set_columns(self, new_columns):
"""
Replace the current column labels with new labels.
Parameters
----------
new_columns : list-like
The new column labels.
"""
if self.has_materialized_columns:
# do not set new columns if they're identical to the previous ones
if (
isinstance(new_columns, pandas.Index)
and self.columns.identical(new_columns)
) or (
not isinstance(new_columns, pandas.Index)
and np.array_equal(self.columns.values, new_columns)
):
return
new_columns = self._validate_set_axis(new_columns, self._columns_cache)
if isinstance(self._dtypes, ModinDtypes):
try:
new_dtypes = self._dtypes.set_index(new_columns)
except NotImplementedError:
# can raise on duplicated labels
new_dtypes = None
elif isinstance(self._dtypes, pandas.Series):
new_dtypes = self.dtypes.set_axis(new_columns)
else:
new_dtypes = None
self.set_columns_cache(new_columns)
# we have to set new dtypes cache after columns,
# so the 'self.columns' and 'new_dtypes.index' indices would match
self.set_dtypes_cache(new_dtypes)
self.synchronize_labels(axis=1)
columns = property(_get_columns, _set_columns)
index = property(_get_index, _set_index)
@property
def axes(self):
"""
Get index and columns that can be accessed with an `axis` integer.
Returns
-------
list
List with two values: index and columns.
"""
return [self.index, self.columns]
def get_axis(self, axis: int = 0) -> pandas.Index:
"""
Get index object for the requested axis.
Parameters
----------
axis : {0, 1}, default: 0
Returns
-------
pandas.Index
"""
return self.index if axis == 0 else self.columns
def _compute_axis_labels_and_lengths(self, axis: int, partitions=None):
"""
Compute the labels for specific `axis`.
Parameters
----------
axis : int
Axis to compute labels along.
partitions : np.ndarray, optional
A 2D NumPy array of partitions from which labels will be grabbed.
If not specified, partitions will be taken from `self._partitions`.
Returns
-------
pandas.Index
Labels for the specified `axis`.
List of int
Size of partitions alongside specified `axis`.
"""
if partitions is None:
partitions = self._partitions
new_index, internal_idx = self._partition_mgr_cls.get_indices(axis, partitions)
return new_index, list(map(len, internal_idx))
def _filter_empties(self, compute_metadata=True):
"""
Remove empty partitions from `self._partitions` to avoid triggering excess computation.
Parameters
----------
compute_metadata : bool, default: True
Trigger the computations for partition sizes and labels if they're not done already.
"""
if not compute_metadata and (
self._row_lengths_cache is None or self._column_widths_cache is None
):
# do not trigger the computations
return
if (
self.has_materialized_index
and len(self.index) == 0
or self.has_materialized_columns
and len(self.columns) == 0
or sum(self.row_lengths) == 0
or sum(self.column_widths) == 0
):
# This is the case for an empty frame. We don't want to completely remove
# all metadata and partitions so for the moment, we won't prune if the frame
# is empty.
# TODO: Handle empty dataframes better
return
self._partitions = np.array(
[
[
self._partitions[i][j]
for j in range(len(self._partitions[i]))
if j < len(self.column_widths) and self.column_widths[j] != 0
]
for i in range(len(self._partitions))
if i < len(self.row_lengths) and self.row_lengths[i] != 0
]
)
new_col_widths = [w for w in self.column_widths if w != 0]
new_row_lengths = [r for r in self.row_lengths if r != 0]
# check whether an axis partitioning was modified and if we should reset the lengths id for 'ModinIndex'
if new_col_widths != self.column_widths:
self.set_columns_cache(self.copy_columns_cache(copy_lengths=False))
if new_row_lengths != self.row_lengths:
self.set_index_cache(self.copy_index_cache(copy_lengths=False))
self._column_widths_cache = new_col_widths
self._row_lengths_cache = new_row_lengths
def synchronize_labels(self, axis=None):
"""
Set the deferred axes variables for the ``PandasDataframe``.
Parameters
----------
axis : int, default: None
The deferred axis.
0 for the index, 1 for the columns.
"""
if axis is None:
self._deferred_index = True
self._deferred_column = True
elif axis == 0:
self._deferred_index = True
else:
self._deferred_column = True
def _propagate_index_objs(self, axis=None):
"""
Synchronize labels by applying the index object for specific `axis` to the `self._partitions` lazily.
Adds `set_axis` function to call-queue of each partition from `self._partitions`
to apply new axis.
Parameters
----------
axis : int, default: None
The axis to apply to. If it's None applies to both axes.
"""
self._filter_empties()
if axis is None or axis == 0:
cum_row_lengths = np.cumsum([0] + self.row_lengths)
if axis is None or axis == 1:
cum_col_widths = np.cumsum([0] + self.column_widths)
if axis is None:
def apply_idx_objs(df, idx, cols):
# We should make at least one copy to avoid the data modification problem
# that may arise when sharing buffers from distributed storage
# (zero-copy pickling).
return df.set_axis(idx, axis="index").set_axis(
cols, axis="columns", copy=False
)
self._partitions = np.array(
[
[
self._partitions[i][j].add_to_apply_calls(
apply_idx_objs,
idx=self.index[
slice(cum_row_lengths[i], cum_row_lengths[i + 1])
],
cols=self.columns[
slice(cum_col_widths[j], cum_col_widths[j + 1])
],
length=self.row_lengths[i],
width=self.column_widths[j],
)
for j in range(len(self._partitions[i]))
]
for i in range(len(self._partitions))
]
)
self._deferred_index = False
self._deferred_column = False
elif axis == 0:
def apply_idx_objs(df, idx):
return df.set_axis(idx, axis="index")
self._partitions = np.array(
[
[
self._partitions[i][j].add_to_apply_calls(
apply_idx_objs,
idx=self.index[
slice(cum_row_lengths[i], cum_row_lengths[i + 1])
],
length=self.row_lengths[i],
width=self.column_widths[j],
)
for j in range(len(self._partitions[i]))
]
for i in range(len(self._partitions))
]
)
self._deferred_index = False
elif axis == 1:
def apply_idx_objs(df, cols):
return df.set_axis(cols, axis="columns")
self._partitions = np.array(
[
[
self._partitions[i][j].add_to_apply_calls(
apply_idx_objs,
cols=self.columns[
slice(cum_col_widths[j], cum_col_widths[j + 1])
],
length=self.row_lengths[i],
width=self.column_widths[j],
)
for j in range(len(self._partitions[i]))
]
for i in range(len(self._partitions))
]
)
self._deferred_column = False
else:
ErrorMessage.catch_bugs_and_request_email(
axis is not None and axis not in [0, 1]
)
@lazy_metadata_decorator(apply_axis=None)
def take_2d_labels_or_positional(
self,
row_labels: Optional[List[Hashable]] = None,
row_positions: Optional[List[int]] = None,
col_labels: Optional[List[Hashable]] = None,
col_positions: Optional[List[int]] = None,
) -> "PandasDataframe":
"""
Lazily select columns or rows from given indices.
Parameters
----------
row_labels : list of hashable, optional
The row labels to extract.
row_positions : list-like of ints, optional
The row positions to extract.
col_labels : list of hashable, optional
The column labels to extract.
col_positions : list-like of ints, optional
The column positions to extract.
Returns
-------
PandasDataframe
A new PandasDataframe from the mask provided.
Notes
-----
If both `row_labels` and `row_positions` are provided, a ValueError is raised.
The same rule applies for `col_labels` and `col_positions`.
"""