-
Notifications
You must be signed in to change notification settings - Fork 172
/
conditional_join.py
2652 lines (2468 loc) · 87.9 KB
/
conditional_join.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
import itertools
import math
import operator
from typing import Any, Hashable, Literal, Optional, Union
import numpy as np
import pandas as pd
import pandas_flavor as pf
from pandas.api.types import (
is_datetime64_dtype,
is_dtype_equal,
is_extension_array_dtype,
is_numeric_dtype,
is_timedelta64_dtype,
)
from pandas.core.dtypes.concat import concat_compat
from pandas.core.reshape.merge import _MergeOperation
from janitor.functions.utils import (
_generic_func_cond_join,
_JoinOperator,
_keep_output,
greater_than_join_types,
less_than_join_types,
)
from janitor.utils import check, check_column
@pf.register_dataframe_method
def conditional_join(
df: pd.DataFrame,
right: Union[pd.DataFrame, pd.Series],
*conditions: Any,
how: Literal["inner", "left", "right", "outer"] = "inner",
df_columns: Optional[Any] = slice(None),
right_columns: Optional[Any] = slice(None),
keep: Literal["first", "last", "all"] = "all",
use_numba: bool = False,
indicator: Optional[Union[bool, str]] = False,
force: bool = False,
) -> pd.DataFrame:
"""The conditional_join function operates similarly to `pd.merge`,
but supports joins on inequality operators,
or a combination of equi and non-equi joins.
Joins solely on equality are not supported.
If the join is solely on equality, `pd.merge` function
covers that; if you are interested in nearest joins, asof joins,
or rolling joins, then `pd.merge_asof` covers that.
There is also pandas' IntervalIndex, which is efficient for range joins,
especially if the intervals do not overlap.
Column selection in `df_columns` and `right_columns` is possible using the
[`select`][janitor.functions.select.select] syntax.
Performance might be improved by setting `use_numba` to `True` -
this can be handy for equi joins that have lots of duplicated keys.
This can also be handy for non-equi joins, where there are more than
two join conditions,
or there is significant overlap in the range join columns.
This assumes that `numba` is installed.
Noticeable performance can be observed for range joins,
if both join columns from the right dataframe
are monotonically increasing.
This function returns rows, if any, where values from `df` meet the
condition(s) for values from `right`. The conditions are passed in
as a variable argument of tuples, where the tuple is of
the form `(left_on, right_on, op)`; `left_on` is the column
label from `df`, `right_on` is the column label from `right`,
while `op` is the operator.
For multiple conditions, the and(`&`)
operator is used to combine the results of the individual conditions.
In some scenarios there might be performance gains if the less than join,
or the greater than join condition, or the range condition
is executed before the equi join - pass `force=True` to force this.
The operator can be any of `==`, `!=`, `<=`, `<`, `>=`, `>`.
There is no optimisation for the `!=` operator.
The join is done only on the columns.
For non-equi joins, only numeric, timedelta and date columns are supported.
`inner`, `left`, `right` and `outer` joins are supported.
If the columns from `df` and `right` have nothing in common,
a single index column is returned; else, a MultiIndex column
is returned.
Examples:
>>> import pandas as pd
>>> import janitor
>>> df1 = pd.DataFrame({"value_1": [2, 5, 7, 1, 3, 4]})
>>> df2 = pd.DataFrame({"value_2A": [0, 3, 7, 12, 0, 2, 3, 1],
... "value_2B": [1, 5, 9, 15, 1, 4, 6, 3],
... })
>>> df1
value_1
0 2
1 5
2 7
3 1
4 3
5 4
>>> df2
value_2A value_2B
0 0 1
1 3 5
2 7 9
3 12 15
4 0 1
5 2 4
6 3 6
7 1 3
>>> df1.conditional_join(
... df2,
... ("value_1", "value_2A", ">"),
... ("value_1", "value_2B", "<")
... )
value_1 value_2A value_2B
0 2 1 3
1 5 3 6
2 3 2 4
3 4 3 5
4 4 3 6
Select specific columns, after the join:
>>> df1.conditional_join(
... df2,
... ("value_1", "value_2A", ">"),
... ("value_1", "value_2B", "<"),
... right_columns='value_2B',
... how='left'
... )
value_1 value_2B
0 2 3.0
1 5 6.0
2 3 4.0
3 4 5.0
4 4 6.0
5 7 NaN
6 1 NaN
Rename columns, before the join:
>>> (df1
... .rename(columns={'value_1':'left_column'})
... .conditional_join(
... df2,
... ("left_column", "value_2A", ">"),
... ("left_column", "value_2B", "<"),
... right_columns='value_2B',
... how='outer')
... )
left_column value_2B
0 2.0 3.0
1 5.0 6.0
2 3.0 4.0
3 4.0 5.0
4 4.0 6.0
5 7.0 NaN
6 1.0 NaN
7 NaN 1.0
8 NaN 9.0
9 NaN 15.0
10 NaN 1.0
Get the first match:
>>> df1.conditional_join(
... df2,
... ("value_1", "value_2A", ">"),
... ("value_1", "value_2B", "<"),
... keep='first'
... )
value_1 value_2A value_2B
0 2 1 3
1 5 3 6
2 3 2 4
3 4 3 5
Get the last match:
>>> df1.conditional_join(
... df2,
... ("value_1", "value_2A", ">"),
... ("value_1", "value_2B", "<"),
... keep='last'
... )
value_1 value_2A value_2B
0 2 1 3
1 5 3 6
2 3 2 4
3 4 3 6
Add an indicator column:
>>> df1.conditional_join(
... df2,
... ("value_1", "value_2A", ">"),
... ("value_1", "value_2B", "<"),
... how='outer',
... indicator=True
... )
value_1 value_2A value_2B _merge
0 2.0 1.0 3.0 both
1 5.0 3.0 6.0 both
2 3.0 2.0 4.0 both
3 4.0 3.0 5.0 both
4 4.0 3.0 6.0 both
5 7.0 NaN NaN left_only
6 1.0 NaN NaN left_only
7 NaN 0.0 1.0 right_only
8 NaN 7.0 9.0 right_only
9 NaN 12.0 15.0 right_only
10 NaN 0.0 1.0 right_only
!!! abstract "Version Changed"
- 0.24.0
- Added `df_columns`, `right_columns`, `keep` and `use_numba` parameters.
- 0.24.1
- Added `indicator` parameter.
- 0.25.0
- `col` class supported.
- Outer join supported. `sort_by_appearance` deprecated.
- Numba support for equi join
- 0.27.0
- Added support for timedelta dtype.
- 0.28.0
- `col` class deprecated.
Args:
df: A pandas DataFrame.
right: Named Series or DataFrame to join to.
conditions: Variable argument of tuple(s) of the form
`(left_on, right_on, op)`, where `left_on` is the column
label from `df`, `right_on` is the column label from `right`,
while `op` is the operator.
The `col` class is also supported. The operator can be any of
`==`, `!=`, `<=`, `<`, `>=`, `>`. For multiple conditions,
the and(`&`) operator is used to combine the results
of the individual conditions.
how: Indicates the type of join to be performed.
It can be one of `inner`, `left`, `right` or `outer`.
df_columns: Columns to select from `df` in the final output dataframe.
Column selection is based on the
[`select`][janitor.functions.select.select] syntax.
right_columns: Columns to select from `right` in the final output dataframe.
Column selection is based on the
[`select`][janitor.functions.select.select] syntax.
use_numba: Use numba, if installed, to accelerate the computation.
keep: Choose whether to return the first match, last match or all matches.
indicator: If `True`, adds a column to the output DataFrame
called `_merge` with information on the source of each row.
The column can be given a different name by providing a string argument.
The column will have a Categorical type with the value of `left_only`
for observations whose merge key only appears in the left DataFrame,
`right_only` for observations whose merge key
only appears in the right DataFrame, and `both` if the observation’s
merge key is found in both DataFrames.
force: If `True`, force the non-equi join conditions to execute before the equi join.
Returns:
A pandas DataFrame of the two merged Pandas objects.
""" # noqa: E501
return _conditional_join_compute(
df=df,
right=right,
conditions=conditions,
how=how,
df_columns=df_columns,
right_columns=right_columns,
keep=keep,
use_numba=use_numba,
indicator=indicator,
force=force,
)
def _check_operator(op: str):
"""
Check that operator is one of
`>`, `>=`, `==`, `!=`, `<`, `<=`.
Used in `conditional_join`.
"""
sequence_of_operators = {op.value for op in _JoinOperator}
if op not in sequence_of_operators:
raise ValueError(
"The conditional join operator "
f"should be one of {sequence_of_operators}"
)
def _conditional_join_preliminary_checks(
df: pd.DataFrame,
right: Union[pd.DataFrame, pd.Series],
conditions: tuple,
how: str,
df_columns: Any,
right_columns: Any,
keep: str,
use_numba: bool,
indicator: Union[bool, str],
force: bool,
return_matching_indices: bool = False,
return_ragged_arrays: bool = False,
) -> tuple:
"""
Preliminary checks for conditional_join are conducted here.
Checks include differences in number of column levels,
length of conditions, existence of columns in dataframe, etc.
"""
check("right", right, [pd.DataFrame, pd.Series])
df = df[:]
right = right[:]
if isinstance(right, pd.Series):
if not right.name:
raise ValueError(
"Unnamed Series are not supported for conditional_join."
)
right = right.to_frame()
if df.columns.nlevels != right.columns.nlevels:
raise ValueError(
"The number of column levels "
"from the left and right frames must match. "
"The number of column levels from the left dataframe "
f"is {df.columns.nlevels}, while the number of column levels "
f"from the right dataframe is {right.columns.nlevels}."
)
if not conditions:
raise ValueError("Kindly provide at least one join condition.")
for condition in conditions:
check("condition", condition, [tuple])
len_condition = len(condition)
if len_condition != 3:
raise ValueError(
"condition should have only three elements; "
f"{condition} however is of length {len_condition}."
)
for left_on, right_on, op in conditions:
check("left_on", left_on, [Hashable])
check("right_on", right_on, [Hashable])
check("operator", op, [str])
check_column(df, [left_on])
check_column(right, [right_on])
_check_operator(op)
if (
all(
(op == _JoinOperator.STRICTLY_EQUAL.value for *_, op in conditions)
)
and not return_matching_indices
):
raise ValueError("Equality only joins are not supported.")
check("how", how, [str])
if how not in {"inner", "left", "right", "outer"}:
raise ValueError(
"'how' should be one of 'inner', 'left', 'right' or 'outer'."
)
if (df.columns.nlevels > 1) and (
isinstance(df_columns, dict) or isinstance(right_columns, dict)
):
raise ValueError(
"Column renaming with a dictionary is not supported "
"for MultiIndex columns."
)
check("keep", keep, [str])
if keep not in {"all", "first", "last"}:
raise ValueError("'keep' should be one of 'all', 'first', 'last'.")
check("use_numba", use_numba, [bool])
check("indicator", indicator, [bool, str])
check("force", force, [bool])
check("return_ragged_arrays", return_ragged_arrays, [bool])
return (
df,
right,
conditions,
how,
df_columns,
right_columns,
keep,
use_numba,
indicator,
force,
return_ragged_arrays,
)
def _conditional_join_type_check(
left_column: pd.Series, right_column: pd.Series, op: str, use_numba: bool
) -> None:
"""
Dtype check for columns in the join.
Checks are not conducted for the equi-join columns,
except when use_numba is set to True.
"""
if (
((op != _JoinOperator.STRICTLY_EQUAL.value) or use_numba)
and not is_numeric_dtype(left_column)
and not is_datetime64_dtype(left_column)
and not is_timedelta64_dtype(left_column)
):
raise TypeError(
"Only numeric, timedelta and datetime types "
"are supported in a non equi-join, "
"or if use_numba is set to True. "
f"{left_column.name} in condition "
f"({left_column.name}, {right_column.name}, {op}) "
f"has a dtype {left_column.dtype}."
)
if (
(op != _JoinOperator.STRICTLY_EQUAL.value) or use_numba
) and not is_dtype_equal(left_column, right_column):
raise TypeError(
f"Both columns should have the same type - "
f"'{left_column.name}' has {left_column.dtype} type;"
f"'{right_column.name}' has {right_column.dtype} type."
)
return None
def _conditional_join_compute(
df: pd.DataFrame,
right: pd.DataFrame,
conditions: list,
how: str,
df_columns: Any,
right_columns: Any,
keep: str,
use_numba: bool,
indicator: Union[bool, str],
force: bool,
return_matching_indices: bool = False,
return_ragged_arrays: bool = False,
) -> pd.DataFrame:
"""
This is where the actual computation
for the conditional join takes place.
"""
(
df,
right,
conditions,
how,
df_columns,
right_columns,
keep,
use_numba,
indicator,
force,
return_ragged_arrays,
) = _conditional_join_preliminary_checks(
df=df,
right=right,
conditions=conditions,
how=how,
df_columns=df_columns,
right_columns=right_columns,
keep=keep,
use_numba=use_numba,
indicator=indicator,
force=force,
return_matching_indices=return_matching_indices,
return_ragged_arrays=return_ragged_arrays,
)
eq_check = False
le_lt_check = False
for condition in conditions:
left_on, right_on, op = condition
_conditional_join_type_check(
left_column=df[left_on],
right_column=right[right_on],
op=op,
use_numba=use_numba,
)
if op == _JoinOperator.STRICTLY_EQUAL.value:
eq_check = True
elif op in less_than_join_types.union(greater_than_join_types):
le_lt_check = True
df.index = range(len(df))
right.index = range(len(right))
if eq_check:
result = _multiple_conditional_join_eq(
df=df,
right=right,
conditions=conditions,
keep=keep,
use_numba=use_numba,
force=force,
return_ragged_arrays=return_ragged_arrays,
)
elif (len(conditions) > 1) & le_lt_check:
result = _multiple_conditional_join_le_lt(
df=df,
right=right,
conditions=conditions,
keep=keep,
use_numba=use_numba,
return_ragged_arrays=return_ragged_arrays,
)
elif len(conditions) > 1:
result = _multiple_conditional_join_ne(
df=df, right=right, conditions=conditions, keep=keep
)
elif use_numba:
result = _numba_single_non_equi_join(
left=df[left_on],
right=right[right_on],
op=op,
keep=keep,
)
else:
result = _generic_func_cond_join(
left=df[left_on],
right=right[right_on],
op=op,
multiple_conditions=False,
keep=keep,
return_ragged_arrays=return_ragged_arrays,
)
if result is None:
result = np.array([], dtype=np.intp), np.array([], dtype=np.intp)
if return_matching_indices:
return result
left_index, right_index = result
return _create_frame(
df=df,
right=right,
left_index=left_index,
right_index=right_index,
how=how,
df_columns=df_columns,
right_columns=right_columns,
indicator=indicator,
)
operator_map = {
_JoinOperator.STRICTLY_EQUAL.value: operator.eq,
_JoinOperator.LESS_THAN.value: operator.lt,
_JoinOperator.LESS_THAN_OR_EQUAL.value: operator.le,
_JoinOperator.GREATER_THAN.value: operator.gt,
_JoinOperator.GREATER_THAN_OR_EQUAL.value: operator.ge,
_JoinOperator.NOT_EQUAL.value: operator.ne,
}
def _generate_indices(
left_index: np.ndarray,
right_index: np.ndarray,
conditions: list[tuple[pd.Series, pd.Series, str]],
) -> tuple:
"""
Run a for loop to get the final indices.
This iteratively goes through each condition,
builds a boolean array,
and gets indices for rows that meet the condition requirements.
`conditions` is a list of tuples, where a tuple is of the form:
`(Series from df, Series from right, operator)`.
"""
for condition in conditions:
left, right, op = condition
left = left._values[left_index]
right = right._values[right_index]
op = operator_map[op]
mask = op(left, right)
if not mask.any():
return None
if is_extension_array_dtype(mask):
mask = mask.to_numpy(dtype=bool, na_value=False)
if not mask.all():
left_index = left_index[mask]
right_index = right_index[mask]
return left_index, right_index
def _multiple_conditional_join_ne(
df: pd.DataFrame,
right: pd.DataFrame,
conditions: list[tuple[pd.Series, pd.Series, str]],
keep: str,
) -> tuple:
"""
Get indices for multiple conditions,
where all the operators are `!=`.
Returns a tuple of (left_index, right_index)
"""
# currently, there is no optimization option here
# not equal typically combines less than
# and greater than, so a lot more rows are returned
# than just less than or greater than
first, *rest = conditions
left_on, right_on, op = first
indices = _generic_func_cond_join(
left=df[left_on],
right=right[right_on],
op=op,
multiple_conditions=False,
keep="all",
)
if indices is None:
return None
rest = (
(df[left_on], right[right_on], op) for left_on, right_on, op in rest
)
indices = _generate_indices(*indices, rest)
if not indices:
return None
return _keep_output(keep, *indices)
def _multiple_conditional_join_eq(
df: pd.DataFrame,
right: pd.DataFrame,
conditions: list,
keep: str,
use_numba: bool,
force: bool,
return_ragged_arrays: bool,
) -> tuple:
"""
Get indices for multiple conditions,
if any of the conditions has an `==` operator.
Returns a tuple of (left_index, right_index)
"""
if force:
return _multiple_conditional_join_le_lt(
df=df,
right=right,
conditions=conditions,
keep=keep,
use_numba=use_numba,
return_ragged_arrays=False,
)
if use_numba:
eqs = None
for left_on, right_on, op in conditions:
if op == _JoinOperator.STRICTLY_EQUAL.value:
eqs = (left_on, right_on, op)
break
le_lt = None
ge_gt = None
for condition in conditions:
*_, op = condition
if op in less_than_join_types:
if le_lt:
continue
le_lt = condition
elif op in greater_than_join_types:
if ge_gt:
continue
ge_gt = condition
if le_lt and ge_gt:
break
if not le_lt and not ge_gt:
raise ValueError(
"At least one less than or greater than "
"join condition should be present when an equi-join "
"is present, and use_numba is set to True."
)
rest = [
condition
for condition in conditions
if condition not in {eqs, le_lt, ge_gt}
]
right_columns = [eqs[1]]
df_columns = [eqs[0]]
# ensure the sort columns are unique
if ge_gt:
if ge_gt[1] not in right_columns:
right_columns.append(ge_gt[1])
if ge_gt[0] not in df_columns:
df_columns.append(ge_gt[0])
if le_lt:
if le_lt[1] not in right_columns:
right_columns.append(le_lt[1])
if le_lt[0] not in df_columns:
df_columns.append(le_lt[0])
right_df = right.loc(axis=1)[right_columns]
left_df = df.loc(axis=1)[df_columns]
any_nulls = left_df.isna().any(axis=1)
if any_nulls.all(axis=None):
return None
if any_nulls.any():
left_df = left_df.loc[~any_nulls]
any_nulls = right_df.isna().any(axis=1)
if any_nulls.all(axis=None):
return None
if any_nulls.any():
right_df = right.loc[~any_nulls]
equi_col = right_columns[0]
# check if the first column is sorted
# if sorted, check if the second column is sorted
# per group in the first column
right_is_sorted = right_df[equi_col].is_monotonic_increasing
if right_is_sorted:
grp = right_df.groupby(equi_col, sort=False)
non_equi_col = right_columns[1]
# groupby.is_monotonic_increasing uses apply under the hood
# the approach used below circumvents the Series creation
# (which isn't required here)
# and just gets a sequence of booleans, before calling `all`
# to get a single True or False.
right_is_sorted = all(
arr.is_monotonic_increasing for _, arr in grp[non_equi_col]
)
if not right_is_sorted:
right_df = right_df.sort_values(right_columns)
indices = _numba_equi_join(
df=left_df, right=right_df, eqs=eqs, ge_gt=ge_gt, le_lt=le_lt
)
if indices is None:
return None
if not rest:
return indices
rest = (
(df[left_on], right[right_on], op)
for left_on, right_on, op in rest
)
indices = _generate_indices(*indices, rest)
if indices is None:
return None
return _keep_output(keep, *indices)
if (
return_ragged_arrays
& (len(conditions) == 1)
& (conditions[0][-1] == _JoinOperator.STRICTLY_EQUAL.value)
):
left_on, right_on, op = conditions[0]
return _generic_func_cond_join(
left=df[left_on],
right=right[right_on],
op=op,
multiple_conditions=True,
keep="all",
return_ragged_arrays=return_ragged_arrays,
)
left_df = df[:]
right_df = right[:]
eqs = [
(left_on, right_on)
for left_on, right_on, op in conditions
if op == _JoinOperator.STRICTLY_EQUAL.value
]
left_on, right_on = zip(*eqs)
left_on = list(set(left_on))
right_on = list(set(right_on))
any_nulls = left_df.loc[:, left_on].isna().any(axis=1)
if any_nulls.all():
return None
if any_nulls.any():
left_df = left_df.loc[~any_nulls]
any_nulls = right_df.loc[:, right_on].isna().any(axis=1)
if any_nulls.all():
return None
if any_nulls.any():
right_df = right_df.loc[~any_nulls]
left_on, right_on = zip(*eqs)
left_on = [*left_on]
right_on = [*right_on]
left_index, right_index = _MergeOperation(
left_df,
right_df,
left_on=left_on,
right_on=right_on,
sort=False,
)._get_join_indexers()
if left_index is not None:
if not left_index.size:
return None
left_index = left_df.index[left_index]
# patch based on updates in internal code
# pandas/core/reshape/merge.py#L1692
# for pandas 2.2
elif left_index is None:
left_index = left_df.index._values
if right_index is not None:
right_index = right_df.index[right_index]
else:
right_index = right_df.index._values
rest = [
(df[left_on], right[right_on], op)
for left_on, right_on, op in conditions
if op != _JoinOperator.STRICTLY_EQUAL.value
]
if not rest:
return _keep_output(keep, left_index, right_index)
indices = _generate_indices(left_index, right_index, rest)
if indices is None:
return None
return _keep_output(keep, *indices)
def _multiple_conditional_join_le_lt(
df: pd.DataFrame,
right: pd.DataFrame,
conditions: list,
keep: str,
use_numba: bool,
return_ragged_arrays: bool,
) -> tuple:
"""
Get indices for multiple conditions,
where `>/>=` or `</<=` is present,
and there is no `==` operator.
Returns a tuple of (df_index, right_index)
"""
if use_numba:
gt_lt = [
condition
for condition in conditions
if condition[-1]
in less_than_join_types.union(greater_than_join_types)
]
conditions = [
condition for condition in conditions if condition not in gt_lt
]
if len(gt_lt) > 1:
first_two = [op for *_, op in gt_lt[:2]]
range_join_ops = itertools.product(
less_than_join_types, greater_than_join_types
)
range_join_ops = map(set, range_join_ops)
is_range_join = set(first_two) in range_join_ops
if is_range_join and (first_two[0] in less_than_join_types):
gt_lt = [gt_lt[1], gt_lt[0], *gt_lt[2:]]
if not conditions:
return _numba_multiple_non_equi_join(
df, right, gt_lt, keep=keep, is_range_join=is_range_join
)
indices = _numba_multiple_non_equi_join(
df, right, gt_lt, keep="all", is_range_join=False
)
else:
left_on, right_on, op = gt_lt[0]
indices = _numba_single_non_equi_join(
df[left_on], right[right_on], op, keep="all"
)
if indices is None:
return None
else:
# there is an opportunity for optimization for range joins
# which is usually `lower_value < value < upper_value`
# or `lower_value < a` and `b < upper_value`
# intervalindex is not used here, as there are scenarios
# where there will be overlapping intervals;
# intervalindex does not offer an efficient way to get
# the indices for overlaps
# also, intervalindex covers only the first option
# i.e => `lower_value < value < upper_value`
# it does not extend to range joins for different columns
# i.e => `lower_value < a` and `b < upper_value`
# the option used for range joins is a simple form
# dependent on sorting and extensible to overlaps
# as well as the second option:
# i.e =>`lower_value < a` and `b < upper_value`
# range joins are also the more common types of non-equi joins
# the other joins do not have an optimisation opportunity
# within this space, as far as I know,
# so a blowup of all the rows is unavoidable.
# first step is to get two conditions, if possible
# where one has a less than operator
# and the other has a greater than operator
# get the indices from that
# and then build the remaining indices,
# using _generate_indices function
# the aim of this for loop is to see if there is
# the possibility of a range join, and if there is,
# then use the optimised path
first_two = [op for *_, op in conditions[:2]]
range_join_ops = itertools.product(
less_than_join_types, greater_than_join_types
)
range_join_ops = map(set, range_join_ops)
is_range_join = set(first_two) in range_join_ops
# optimised path
if is_range_join:
if first_two[0] in less_than_join_types:
le_lt, ge_gt = conditions[:2]
else:
ge_gt, le_lt = conditions[:2]
conditions = [
condition
for condition in conditions
if condition not in (ge_gt, le_lt)
]
if conditions:
_keep = None
return_ragged_arrays = False
right_is_sorted = False
else:
first = ge_gt[1]
second = le_lt[1]
right_is_sorted = (
right[first].is_monotonic_increasing
& right[second].is_monotonic_increasing
)
if right_is_sorted:
_keep = keep
else:
_keep = None
indices = _range_indices(
df=df,
right=right,
first=ge_gt,
second=le_lt,
keep=_keep,
return_ragged_arrays=return_ragged_arrays,
right_is_sorted=right_is_sorted,
)
if indices is None:
return None
if _keep or (return_ragged_arrays & isinstance(indices[1], list)):
return indices
# no optimised path
# blow up the rows and prune
else:
lt_or_gt = None
for condition in conditions:
if condition[-1] in less_than_join_types.union(
greater_than_join_types
):
lt_or_gt = condition
break
conditions = [
condition for condition in conditions if condition != lt_or_gt
]
left_on, right_on, op = lt_or_gt
indices = _generic_func_cond_join(
left=df[left_on],
right=right[right_on],
op=op,
multiple_conditions=False,
keep="all",
)