-
-
Notifications
You must be signed in to change notification settings - Fork 18.4k
/
Copy pathindexing.py
2775 lines (2278 loc) · 93.9 KB
/
indexing.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 contextlib import suppress
import sys
from typing import (
TYPE_CHECKING,
Any,
TypeVar,
cast,
final,
)
import warnings
import numpy as np
from pandas._libs.indexing import NDFrameIndexerBase
from pandas._libs.lib import item_from_zerodim
from pandas.compat import PYPY
from pandas.errors import (
AbstractMethodError,
ChainedAssignmentError,
IndexingError,
InvalidIndexError,
LossySetitemError,
)
from pandas.errors.cow import _chained_assignment_msg
from pandas.util._decorators import doc
from pandas.core.dtypes.cast import (
can_hold_element,
maybe_promote,
)
from pandas.core.dtypes.common import (
is_array_like,
is_bool_dtype,
is_hashable,
is_integer,
is_iterator,
is_list_like,
is_numeric_dtype,
is_object_dtype,
is_scalar,
is_sequence,
)
from pandas.core.dtypes.concat import concat_compat
from pandas.core.dtypes.dtypes import ExtensionDtype
from pandas.core.dtypes.generic import (
ABCDataFrame,
ABCSeries,
)
from pandas.core.dtypes.missing import (
construct_1d_array_from_inferred_fill_value,
infer_fill_value,
is_valid_na_for_dtype,
isna,
na_value_for_dtype,
)
from pandas.core import algorithms as algos
import pandas.core.common as com
from pandas.core.construction import (
array as pd_array,
extract_array,
)
from pandas.core.indexers import (
check_array_indexer,
is_list_like_indexer,
is_scalar_indexer,
length_of_indexer,
)
from pandas.core.indexes.api import (
Index,
MultiIndex,
)
if TYPE_CHECKING:
from collections.abc import (
Hashable,
Sequence,
)
from pandas._typing import (
Axis,
AxisInt,
Self,
npt,
)
from pandas import (
DataFrame,
Series,
)
T = TypeVar("T")
# "null slice"
_NS = slice(None, None)
_one_ellipsis_message = "indexer may only contain one '...' entry"
# the public IndexSlicerMaker
class _IndexSlice:
"""
Create an object to more easily perform multi-index slicing.
See Also
--------
MultiIndex.remove_unused_levels : New MultiIndex with no unused levels.
Notes
-----
See :ref:`Defined Levels <advanced.shown_levels>`
for further info on slicing a MultiIndex.
Examples
--------
>>> midx = pd.MultiIndex.from_product([["A0", "A1"], ["B0", "B1", "B2", "B3"]])
>>> columns = ["foo", "bar"]
>>> dfmi = pd.DataFrame(
... np.arange(16).reshape((len(midx), len(columns))),
... index=midx,
... columns=columns,
... )
Using the default slice command:
>>> dfmi.loc[(slice(None), slice("B0", "B1")), :]
foo bar
A0 B0 0 1
B1 2 3
A1 B0 8 9
B1 10 11
Using the IndexSlice class for a more intuitive command:
>>> idx = pd.IndexSlice
>>> dfmi.loc[idx[:, "B0":"B1"], :]
foo bar
A0 B0 0 1
B1 2 3
A1 B0 8 9
B1 10 11
"""
def __getitem__(self, arg):
return arg
IndexSlice = _IndexSlice()
class IndexingMixin:
"""
Mixin for adding .loc/.iloc/.at/.iat to Dataframes and Series.
"""
@property
def iloc(self) -> _iLocIndexer:
"""
Purely integer-location based indexing for selection by position.
.. versionchanged:: 3.0
Callables which return a tuple are deprecated as input.
``.iloc[]`` is primarily integer position based (from ``0`` to
``length-1`` of the axis), but may also be used with a boolean
array.
Allowed inputs are:
- An integer, e.g. ``5``.
- A list or array of integers, e.g. ``[4, 3, 0]``.
- A slice object with ints, e.g. ``1:7``.
- A boolean array.
- A ``callable`` function with one argument (the calling Series or
DataFrame) and that returns valid output for indexing (one of the above).
This is useful in method chains, when you don't have a reference to the
calling object, but would like to base your selection on
some value.
- A tuple of row and column indexes. The tuple elements consist of one of the
above inputs, e.g. ``(0, 1)``.
``.iloc`` will raise ``IndexError`` if a requested indexer is
out-of-bounds, except *slice* indexers which allow out-of-bounds
indexing (this conforms with python/numpy *slice* semantics).
See more at :ref:`Selection by Position <indexing.integer>`.
See Also
--------
DataFrame.iat : Fast integer location scalar accessor.
DataFrame.loc : Purely label-location based indexer for selection by label.
Series.iloc : Purely integer-location based indexing for
selection by position.
Examples
--------
>>> mydict = [
... {"a": 1, "b": 2, "c": 3, "d": 4},
... {"a": 100, "b": 200, "c": 300, "d": 400},
... {"a": 1000, "b": 2000, "c": 3000, "d": 4000},
... ]
>>> df = pd.DataFrame(mydict)
>>> df
a b c d
0 1 2 3 4
1 100 200 300 400
2 1000 2000 3000 4000
**Indexing just the rows**
With a scalar integer.
>>> type(df.iloc[0])
<class 'pandas.Series'>
>>> df.iloc[0]
a 1
b 2
c 3
d 4
Name: 0, dtype: int64
With a list of integers.
>>> df.iloc[[0]]
a b c d
0 1 2 3 4
>>> type(df.iloc[[0]])
<class 'pandas.DataFrame'>
>>> df.iloc[[0, 1]]
a b c d
0 1 2 3 4
1 100 200 300 400
With a `slice` object.
>>> df.iloc[:3]
a b c d
0 1 2 3 4
1 100 200 300 400
2 1000 2000 3000 4000
With a boolean mask the same length as the index.
>>> df.iloc[[True, False, True]]
a b c d
0 1 2 3 4
2 1000 2000 3000 4000
With a callable, useful in method chains. The `x` passed
to the ``lambda`` is the DataFrame being sliced. This selects
the rows whose index label even.
>>> df.iloc[lambda x: x.index % 2 == 0]
a b c d
0 1 2 3 4
2 1000 2000 3000 4000
**Indexing both axes**
You can mix the indexer types for the index and columns. Use ``:`` to
select the entire axis.
With scalar integers.
>>> df.iloc[0, 1]
2
With lists of integers.
>>> df.iloc[[0, 2], [1, 3]]
b d
0 2 4
2 2000 4000
With `slice` objects.
>>> df.iloc[1:3, 0:3]
a b c
1 100 200 300
2 1000 2000 3000
With a boolean array whose length matches the columns.
>>> df.iloc[:, [True, False, True, False]]
a c
0 1 3
1 100 300
2 1000 3000
With a callable function that expects the Series or DataFrame.
>>> df.iloc[:, lambda df: [0, 2]]
a c
0 1 3
1 100 300
2 1000 3000
"""
return _iLocIndexer("iloc", self)
@property
def loc(self) -> _LocIndexer:
"""
Access a group of rows and columns by label(s) or a boolean array.
``.loc[]`` is primarily label based, but may also be used with a
boolean array.
Allowed inputs are:
- A single label, e.g. ``5`` or ``'a'``, (note that ``5`` is
interpreted as a *label* of the index, and **never** as an
integer position along the index).
- A list or array of labels, e.g. ``['a', 'b', 'c']``.
- A slice object with labels, e.g. ``'a':'f'``.
.. warning:: Note that contrary to usual python slices, **both** the
start and the stop are included
- A boolean array of the same length as the axis being sliced,
e.g. ``[True, False, True]``.
- An alignable boolean Series. The index of the key will be aligned before
masking.
- An alignable Index. The Index of the returned selection will be the input.
- A ``callable`` function with one argument (the calling Series or
DataFrame) and that returns valid output for indexing (one of the above)
See more at :ref:`Selection by Label <indexing.label>`.
Raises
------
KeyError
If any items are not found.
IndexingError
If an indexed key is passed and its index is unalignable to the frame index.
See Also
--------
DataFrame.at : Access a single value for a row/column label pair.
DataFrame.iloc : Access group of rows and columns by integer position(s).
DataFrame.xs : Returns a cross-section (row(s) or column(s)) from the
Series/DataFrame.
Series.loc : Access group of values using labels.
Examples
--------
**Getting values**
>>> df = pd.DataFrame(
... [[1, 2], [4, 5], [7, 8]],
... index=["cobra", "viper", "sidewinder"],
... columns=["max_speed", "shield"],
... )
>>> df
max_speed shield
cobra 1 2
viper 4 5
sidewinder 7 8
Single label. Note this returns the row as a Series.
>>> df.loc["viper"]
max_speed 4
shield 5
Name: viper, dtype: int64
List of labels. Note using ``[[]]`` returns a DataFrame.
>>> df.loc[["viper", "sidewinder"]]
max_speed shield
viper 4 5
sidewinder 7 8
Single label for row and column
>>> df.loc["cobra", "shield"]
2
Slice with labels for row and single label for column. As mentioned
above, note that both the start and stop of the slice are included.
>>> df.loc["cobra":"viper", "max_speed"]
cobra 1
viper 4
Name: max_speed, dtype: int64
Boolean list with the same length as the row axis
>>> df.loc[[False, False, True]]
max_speed shield
sidewinder 7 8
Alignable boolean Series:
>>> df.loc[
... pd.Series([False, True, False], index=["viper", "sidewinder", "cobra"])
... ]
max_speed shield
sidewinder 7 8
Index (same behavior as ``df.reindex``)
>>> df.loc[pd.Index(["cobra", "viper"], name="foo")]
max_speed shield
foo
cobra 1 2
viper 4 5
Conditional that returns a boolean Series
>>> df.loc[df["shield"] > 6]
max_speed shield
sidewinder 7 8
Conditional that returns a boolean Series with column labels specified
>>> df.loc[df["shield"] > 6, ["max_speed"]]
max_speed
sidewinder 7
Multiple conditional using ``&`` that returns a boolean Series
>>> df.loc[(df["max_speed"] > 1) & (df["shield"] < 8)]
max_speed shield
viper 4 5
Multiple conditional using ``|`` that returns a boolean Series
>>> df.loc[(df["max_speed"] > 4) | (df["shield"] < 5)]
max_speed shield
cobra 1 2
sidewinder 7 8
Please ensure that each condition is wrapped in parentheses ``()``.
See the :ref:`user guide<indexing.boolean>`
for more details and explanations of Boolean indexing.
.. note::
If you find yourself using 3 or more conditionals in ``.loc[]``,
consider using :ref:`advanced indexing<advanced.advanced_hierarchical>`.
See below for using ``.loc[]`` on MultiIndex DataFrames.
Callable that returns a boolean Series
>>> df.loc[lambda df: df["shield"] == 8]
max_speed shield
sidewinder 7 8
**Setting values**
Set value for all items matching the list of labels
>>> df.loc[["viper", "sidewinder"], ["shield"]] = 50
>>> df
max_speed shield
cobra 1 2
viper 4 50
sidewinder 7 50
Set value for an entire row
>>> df.loc["cobra"] = 10
>>> df
max_speed shield
cobra 10 10
viper 4 50
sidewinder 7 50
Set value for an entire column
>>> df.loc[:, "max_speed"] = 30
>>> df
max_speed shield
cobra 30 10
viper 30 50
sidewinder 30 50
Set value for rows matching callable condition
>>> df.loc[df["shield"] > 35] = 0
>>> df
max_speed shield
cobra 30 10
viper 0 0
sidewinder 0 0
Add value matching location
>>> df.loc["viper", "shield"] += 5
>>> df
max_speed shield
cobra 30 10
viper 0 5
sidewinder 0 0
Setting using a ``Series`` or a ``DataFrame`` sets the values matching the
index labels, not the index positions.
>>> shuffled_df = df.loc[["viper", "cobra", "sidewinder"]]
>>> df.loc[:] += shuffled_df
>>> df
max_speed shield
cobra 60 20
viper 0 10
sidewinder 0 0
**Getting values on a DataFrame with an index that has integer labels**
Another example using integers for the index
>>> df = pd.DataFrame(
... [[1, 2], [4, 5], [7, 8]],
... index=[7, 8, 9],
... columns=["max_speed", "shield"],
... )
>>> df
max_speed shield
7 1 2
8 4 5
9 7 8
Slice with integer labels for rows. As mentioned above, note that both
the start and stop of the slice are included.
>>> df.loc[7:9]
max_speed shield
7 1 2
8 4 5
9 7 8
**Getting values with a MultiIndex**
A number of examples using a DataFrame with a MultiIndex
>>> tuples = [
... ("cobra", "mark i"),
... ("cobra", "mark ii"),
... ("sidewinder", "mark i"),
... ("sidewinder", "mark ii"),
... ("viper", "mark ii"),
... ("viper", "mark iii"),
... ]
>>> index = pd.MultiIndex.from_tuples(tuples)
>>> values = [[12, 2], [0, 4], [10, 20], [1, 4], [7, 1], [16, 36]]
>>> df = pd.DataFrame(values, columns=["max_speed", "shield"], index=index)
>>> df
max_speed shield
cobra mark i 12 2
mark ii 0 4
sidewinder mark i 10 20
mark ii 1 4
viper mark ii 7 1
mark iii 16 36
Single label. Note this returns a DataFrame with a single index.
>>> df.loc["cobra"]
max_speed shield
mark i 12 2
mark ii 0 4
Single index tuple. Note this returns a Series.
>>> df.loc[("cobra", "mark ii")]
max_speed 0
shield 4
Name: (cobra, mark ii), dtype: int64
Single label for row and column. Similar to passing in a tuple, this
returns a Series.
>>> df.loc["cobra", "mark i"]
max_speed 12
shield 2
Name: (cobra, mark i), dtype: int64
Single tuple. Note using ``[[]]`` returns a DataFrame.
>>> df.loc[[("cobra", "mark ii")]]
max_speed shield
cobra mark ii 0 4
Single tuple for the index with a single label for the column
>>> df.loc[("cobra", "mark i"), "shield"]
2
Slice from index tuple to single label
>>> df.loc[("cobra", "mark i") : "viper"]
max_speed shield
cobra mark i 12 2
mark ii 0 4
sidewinder mark i 10 20
mark ii 1 4
viper mark ii 7 1
mark iii 16 36
Slice from index tuple to index tuple
>>> df.loc[("cobra", "mark i") : ("viper", "mark ii")]
max_speed shield
cobra mark i 12 2
mark ii 0 4
sidewinder mark i 10 20
mark ii 1 4
viper mark ii 7 1
Please see the :ref:`user guide<advanced.advanced_hierarchical>`
for more details and explanations of advanced indexing.
"""
return _LocIndexer("loc", self)
@property
def at(self) -> _AtIndexer:
"""
Access a single value for a row/column label pair.
Similar to ``loc``, in that both provide label-based lookups. Use
``at`` if you only need to get or set a single value in a DataFrame
or Series.
Raises
------
KeyError
If getting a value and 'label' does not exist in a DataFrame or Series.
ValueError
If row/column label pair is not a tuple or if any label
from the pair is not a scalar for DataFrame.
If label is list-like (*excluding* NamedTuple) for Series.
See Also
--------
DataFrame.at : Access a single value for a row/column pair by label.
DataFrame.iat : Access a single value for a row/column pair by integer
position.
DataFrame.loc : Access a group of rows and columns by label(s).
DataFrame.iloc : Access a group of rows and columns by integer
position(s).
Series.at : Access a single value by label.
Series.iat : Access a single value by integer position.
Series.loc : Access a group of rows by label(s).
Series.iloc : Access a group of rows by integer position(s).
Notes
-----
See :ref:`Fast scalar value getting and setting <indexing.basics.get_value>`
for more details.
Examples
--------
>>> df = pd.DataFrame(
... [[0, 2, 3], [0, 4, 1], [10, 20, 30]],
... index=[4, 5, 6],
... columns=["A", "B", "C"],
... )
>>> df
A B C
4 0 2 3
5 0 4 1
6 10 20 30
Get value at specified row/column pair
>>> df.at[4, "B"]
2
Set value at specified row/column pair
>>> df.at[4, "B"] = 10
>>> df.at[4, "B"]
10
Get value within a Series
>>> df.loc[5].at["B"]
4
"""
return _AtIndexer("at", self)
@property
def iat(self) -> _iAtIndexer:
"""
Access a single value for a row/column pair by integer position.
Similar to ``iloc``, in that both provide integer-based lookups. Use
``iat`` if you only need to get or set a single value in a DataFrame
or Series.
Raises
------
IndexError
When integer position is out of bounds.
See Also
--------
DataFrame.at : Access a single value for a row/column label pair.
DataFrame.loc : Access a group of rows and columns by label(s).
DataFrame.iloc : Access a group of rows and columns by integer position(s).
Examples
--------
>>> df = pd.DataFrame(
... [[0, 2, 3], [0, 4, 1], [10, 20, 30]], columns=["A", "B", "C"]
... )
>>> df
A B C
0 0 2 3
1 0 4 1
2 10 20 30
Get value at specified row/column pair
>>> df.iat[1, 2]
1
Set value at specified row/column pair
>>> df.iat[1, 2] = 10
>>> df.iat[1, 2]
10
Get value within a series
>>> df.loc[0].iat[1]
2
"""
return _iAtIndexer("iat", self)
class _LocationIndexer(NDFrameIndexerBase):
_valid_types: str
axis: AxisInt | None = None
# sub-classes need to set _takeable
_takeable: bool
@final
def __call__(self, axis: Axis | None = None) -> Self:
# we need to return a copy of ourselves
new_self = type(self)(self.name, self.obj)
if axis is not None:
axis_int_none = self.obj._get_axis_number(axis)
else:
axis_int_none = axis
new_self.axis = axis_int_none
return new_self
def _get_setitem_indexer(self, key):
"""
Convert a potentially-label-based key into a positional indexer.
"""
if self.name == "loc":
# always holds here bc iloc overrides _get_setitem_indexer
self._ensure_listlike_indexer(key, axis=self.axis)
if isinstance(key, tuple):
for x in key:
check_dict_or_set_indexers(x)
if self.axis is not None:
key = _tupleize_axis_indexer(self.ndim, self.axis, key)
ax = self.obj._get_axis(0)
if (
isinstance(ax, MultiIndex)
and self.name != "iloc"
and is_hashable(key)
and not isinstance(key, slice)
):
with suppress(KeyError, InvalidIndexError):
# TypeError e.g. passed a bool
return ax.get_loc(key)
if isinstance(key, tuple):
with suppress(IndexingError):
# suppress "Too many indexers"
return self._convert_tuple(key)
if isinstance(key, range):
# GH#45479 test_loc_setitem_range_key
key = list(key)
return self._convert_to_indexer(key, axis=0)
@final
def _maybe_mask_setitem_value(self, indexer, value):
"""
If we have obj.iloc[mask] = series_or_frame and series_or_frame has the
same length as obj, we treat this as obj.iloc[mask] = series_or_frame[mask],
similar to Series.__setitem__.
Note this is only for loc, not iloc.
"""
if (
isinstance(indexer, tuple)
and len(indexer) == 2
and isinstance(value, (ABCSeries, ABCDataFrame))
):
pi, icols = indexer
ndim = value.ndim
if com.is_bool_indexer(pi) and len(value) == len(pi):
newkey = pi.nonzero()[0]
if is_scalar_indexer(icols, self.ndim - 1) and ndim == 1:
# e.g. test_loc_setitem_boolean_mask_allfalse
if len(newkey) == 0:
value = value.iloc[:0]
else:
# test_loc_setitem_ndframe_values_alignment
value = self.obj.iloc._align_series(indexer, value)
indexer = (newkey, icols)
elif (
isinstance(icols, np.ndarray)
and icols.dtype.kind == "i"
and len(icols) == 1
):
if ndim == 1:
# We implicitly broadcast, though numpy does not, see
# github.com/pandas-dev/pandas/pull/45501#discussion_r789071825
# test_loc_setitem_ndframe_values_alignment
value = self.obj.iloc._align_series(indexer, value)
indexer = (newkey, icols)
elif ndim == 2 and value.shape[1] == 1:
if len(newkey) == 0:
value = value.iloc[:0]
else:
# test_loc_setitem_ndframe_values_alignment
value = self.obj.iloc._align_frame(indexer, value)
indexer = (newkey, icols)
elif com.is_bool_indexer(indexer):
indexer = indexer.nonzero()[0]
return indexer, value
@final
def _ensure_listlike_indexer(self, key, axis=None, value=None) -> None:
"""
Ensure that a list-like of column labels are all present by adding them if
they do not already exist.
Parameters
----------
key : list-like of column labels
Target labels.
axis : key axis if known
"""
column_axis = 1
# column only exists in 2-dimensional DataFrame
if self.ndim != 2:
return
if isinstance(key, tuple) and len(key) > 1:
# key may be a tuple if we are .loc
# if length of key is > 1 set key to column part
# unless axis is already specified, then go with that
if axis is None:
axis = column_axis
key = key[axis]
if (
axis == column_axis
and not isinstance(self.obj.columns, MultiIndex)
and is_list_like_indexer(key)
and not com.is_bool_indexer(key)
and all(is_hashable(k) for k in key)
):
# GH#38148
keys = self.obj.columns.union(key, sort=False)
diff = Index(key).difference(self.obj.columns, sort=False)
if len(diff):
# e.g. if we are doing df.loc[:, ["A", "B"]] = 7 and "B"
# is a new column, add the new columns with dtype=np.void
# so that later when we go through setitem_single_column
# we will use isetitem. Without this, the reindex_axis
# below would create float64 columns in this example, which
# would successfully hold 7, so we would end up with the wrong
# dtype.
indexer = np.arange(len(keys), dtype=np.intp)
indexer[len(self.obj.columns) :] = -1
new_mgr = self.obj._mgr.reindex_indexer(
keys, indexer=indexer, axis=0, only_slice=True, use_na_proxy=True
)
self.obj._mgr = new_mgr
return
self.obj._mgr = self.obj._mgr.reindex_axis(keys, axis=0, only_slice=True)
@final
def __setitem__(self, key, value) -> None:
if not PYPY:
if sys.getrefcount(self.obj) <= 2:
warnings.warn(
_chained_assignment_msg, ChainedAssignmentError, stacklevel=2
)
check_dict_or_set_indexers(key)
if isinstance(key, tuple):
key = (list(x) if is_iterator(x) else x for x in key)
key = tuple(com.apply_if_callable(x, self.obj) for x in key)
else:
maybe_callable = com.apply_if_callable(key, self.obj)
key = self._raise_callable_usage(key, maybe_callable)
indexer = self._get_setitem_indexer(key)
self._has_valid_setitem_indexer(key)
iloc: _iLocIndexer = (
cast("_iLocIndexer", self) if self.name == "iloc" else self.obj.iloc
)
iloc._setitem_with_indexer(indexer, value, self.name)
def _validate_key(self, key, axis: AxisInt) -> None:
"""
Ensure that key is valid for current indexer.
Parameters
----------
key : scalar, slice or list-like
Key requested.
axis : int
Dimension on which the indexing is being made.
Raises
------
TypeError
If the key (or some element of it) has wrong type.
IndexError
If the key (or some element of it) is out of bounds.
KeyError
If the key was not found.
"""
raise AbstractMethodError(self)
@final
def _expand_ellipsis(self, tup: tuple) -> tuple:
"""
If a tuple key includes an Ellipsis, replace it with an appropriate
number of null slices.
"""
if any(x is Ellipsis for x in tup):
if tup.count(Ellipsis) > 1:
raise IndexingError(_one_ellipsis_message)
if len(tup) == self.ndim:
# It is unambiguous what axis this Ellipsis is indexing,
# treat as a single null slice.
i = tup.index(Ellipsis)
# FIXME: this assumes only one Ellipsis
new_key = tup[:i] + (_NS,) + tup[i + 1 :]
return new_key
# TODO: other cases? only one test gets here, and that is covered
# by _validate_key_length
return tup
@final
def _validate_tuple_indexer(self, key: tuple) -> tuple:
"""
Check the key for valid keys across my indexer.
"""
key = self._validate_key_length(key)
key = self._expand_ellipsis(key)
for i, k in enumerate(key):
try:
self._validate_key(k, i)
except ValueError as err:
raise ValueError(
f"Location based indexing can only have [{self._valid_types}] types"
) from err
return key
@final
def _is_nested_tuple_indexer(self, tup: tuple) -> bool:
"""
Returns
-------
bool
"""
if any(isinstance(ax, MultiIndex) for ax in self.obj.axes):
return any(is_nested_tuple(tup, ax) for ax in self.obj.axes)
return False
@final
def _convert_tuple(self, key: tuple) -> tuple:
# Note: we assume _tupleize_axis_indexer has been called, if necessary.
self._validate_key_length(key)
keyidx = [self._convert_to_indexer(k, axis=i) for i, k in enumerate(key)]
return tuple(keyidx)
@final