This PR (#56115) introduces performance improvements for merge operations in pandas, specifically when joining on sorted (monotonic) keys. Here's a breakdown of the changes and why they're complex:
Key Changes:
Optimization for Sorted Keys:
Added special handling in get_join_indexers function to detect when both left and right keys are monotonic increasing and one of them is unique
In such cases, uses Index.join with return_indexers=True which is more efficient than the previous approach
This optimization can significantly speed up merge operations on sorted data
Indexer Handling Changes:
Modified the handling of indexers to allow them to be None in cases where no remapping is needed (e.g., when using full ranges)
Added new function get_join_indexers_non_unique to handle the non-optimized path
Changed return types and handling throughout the merge code to accommodate None indexers
Performance Testing:
Added monotonic parameter to merge benchmarks to test both sorted and unsorted cases
Updated ASV benchmarks to measure the impact of the optimizations
Bug Fixes and Edge Cases:
Fixed handling of cases where one side has all missing values
Improved handling of categorical and datetime dtypes
Added proper handling of range indexers
Why It's Complex:
Multiple Code Paths:
The merge operation now has multiple code paths depending on whether keys are sorted/unique
Each path needs to handle all join types (inner, outer, left, right)
Need to ensure consistent behavior across all paths
Type System Complexity:
The changes required modifying type hints to handle Optional indexers
Type system needed to accommodate both array and None types for indexers
Edge Cases:
Many edge cases to consider:
All-missing indexers
Different data types
Empty DataFrames
Duplicate keys
Various join types
Performance Implications:
Changes needed to be carefully benchmarked to ensure they actually improve performance
Had to consider both sorted and unsorted cases
Needed to avoid performance regressions in any scenario
Backward Compatibility:
Changes needed to maintain backward compatibility with existing behavior
Had to ensure all existing tests still pass
Performance Impact:
The benchmark results show significant improvements:
merge_ordered: 389ms → 10ms (39x faster)
Regular merge: 173ms → 10.7ms (16x faster)
Various other merge operations showing 2-3x improvements
This optimization is particularly valuable for time series data where keys are often sorted timestamps, making it a common and impactful improvement for pandas users.
The complexity comes from maintaining all existing functionality while adding new optimized paths, ensuring type safety, handling edge cases, and validating performance improvements across different scenarios.
Great question! The performance improvement comes from leveraging the properties of sorted (monotonic) data and unique keys. Let me break it down step by step:
What Was the Previous Approach?
The previous implementation in get_join_indexers used a general-purpose algorithm that worked for all cases, including unsorted and non-unique keys. Here's what it did:
Factorize the keys:
Convert the keys (left and right) into integer-based labels using _factorize_keys.
This involves hashing and mapping the keys to a dense integer space.
Compute join indexers:
Use low-level join functions (libjoin.inner_join, libjoin.left_outer_join, etc.) to compute the indexers (mappings between left and right keys).
These functions perform a merge-like operation on the integer labels to find matches.
This approach is robust but computationally expensive because:
It requires hashing and factorization of keys, even if they are already sorted.
It doesn't take advantage of the sorted nature of the data, which could allow for more efficient algorithms.
Why is Index.join Faster for Sorted Keys?
The new approach uses Index.join with return_indexers=True when the keys are sorted and one of them is unique. Here's why this is faster:
Sorted Data Enables Binary Search:
When keys are sorted, you can use binary search (O(log n)) to find matches instead of linear search (O(n)).
Binary search is much faster for large datasets because it reduces the number of comparisons needed.
Unique Keys Simplify the Problem:
If one of the keys is unique, you don't need to handle duplicates, which simplifies the matching process.
For example, if the left key is unique, each right key can match at most one left key.
Index.join is Optimized for Sorted Data:
The Index.join method is specifically designed to handle sorted data efficiently.
It uses merge-like algorithms that take advantage of the sorted nature of the data, avoiding unnecessary hashing and factorization.
No Need for Hashing or Factorization:
Since the keys are already sorted, you can directly compare them without converting them into integer labels.
This skips the expensive _factorize_keys step.
Efficient Indexer Computation:
Index.join computes the indexers (mappings between left and right keys) using a single pass over the sorted data.
This is much faster than the previous approach, which required multiple steps (factorization, join on integer labels, etc.).
How Does Index.join Work Internally?
When you call Index.join with return_indexers=True, it:
Checks if the data is sorted:
Uses is_monotonic_increasing to confirm the keys are sorted.
Performs a merge-like operation:
Iterates through both sorted keys simultaneously, comparing them using binary search.
For each match, it records the corresponding indices (indexers).
Handles join types:
Depending on the join type (inner, left, right, outer), it adjusts the indexers to include/exclude unmatched keys.
This process is linear in complexity (O(n)) for sorted data, compared to the previous approach, which could be O(n log n) or worse due to hashing and factorization.
Why is This Optimization Significant?
Time Series Data:
Many real-world datasets (e.g., financial data, sensor data) are sorted by timestamps.
This optimization makes merges on such data significantly faster.
Large Datasets:
The performance gains are more pronounced for larger datasets, where the overhead of hashing and factorization becomes significant.
Common Use Case:
Merging on sorted keys is a very common operation, so this optimization benefits a wide range of users.
# Check if keys are sorted and unique
if left.is_monotonic_increasing and right.is_monotonic_increasing:
# Use Index.join (optimized for sorted data)
_, left_indexer, right_indexer = left.join(right, how="inner", return_indexers=True)
The new approach avoids the factorization step and uses a more efficient algorithm for sorted data.
Summary
The key reason Index.join is faster is that it leverages the sorted nature of the data to use more efficient algorithms (binary search, merge-like operations) and avoids unnecessary hashing and factorization. This makes it particularly well-suited for time series and other sorted datasets, where it can provide order-of-magnitude speedups.
Great question! Let me clarify the core optimization in this PR and how it relates to binary search and Index.join.
The Optimization in a Nutshell
The optimization is using Index.join for sorted keys, which internally leverages merge-like algorithms (not strictly binary search). Here's the breakdown:
When the keys are sorted and one of them is unique:
The code calls Index.join with return_indexers=True.
Index.join uses an efficient merge-like algorithm to compute the indexers (mappings between left and right keys).
When the keys are not sorted or not unique:
The code falls back to the previous approach (factorization + join on integer labels).
Is It Using Binary Search?
Not directly. The optimization doesn't explicitly use binary search, but it leverages the sorted nature of the data to enable a merge-like algorithm, which is similarly efficient.
Binary Search:
Binary search is typically used to find a single value in a sorted array (O(log n)).
It's not directly applicable for joining two sorted arrays because you need to find all matches, not just one.
Merge-like Algorithm:
A merge-like algorithm iterates through both sorted arrays simultaneously in a single pass (O(n)).
It compares elements at the current positions and advances the pointer with the smaller value.
This is the approach used by Index.join for sorted data.
So, while binary search isn't used directly, the optimization achieves similar efficiency by leveraging the sorted property of the data.
Is It Using Index.join?
Yes, the core optimization is using Index.join for sorted keys. Here's why:
Index.join is Optimized for Sorted Data:
When you call Index.join on sorted indices, it uses a merge-like algorithm to compute the indexers efficiently.
This avoids the need for hashing and factorization, which are expensive operations.
How Index.join Works:
It iterates through both sorted indices simultaneously.
For each pair of elements, it compares them and records the matches (indexers).
This is much faster than the previous approach, which involved:
Hashing and factorizing the keys.
Performing a join on the integer labels.
Why Index.join is Faster:
It skips the expensive factorization step.
It uses the sorted property to compute the indexers in a single pass (O(n)).
Why Not Just Use Binary Search?
Binary search is great for finding a single value in a sorted array, but it's not ideal for joining two sorted arrays because:
You need to find all matches, not just one.
Binary search would require multiple searches (one for each key), which would be slower than a single-pass merge-like algorithm.
The merge-like algorithm used by Index.join is more appropriate for this task because it:
Processes both arrays in a single pass.
Handles all matches efficiently.
Summary
The optimization is using Index.join for sorted keys.
Index.join internally uses a merge-like algorithm (not binary search) to compute the indexers efficiently.
This is faster than the previous approach because:
It avoids hashing and factorization.
It leverages the sorted nature of the data to compute the indexers in a single pass.
So, the optimization is not about binary search, but about using Index.join for sorted keys, which is itself optimized for this scenario.
Yes, the optimization in this PR is related to merge sort in concept, but it's not exactly the same. Let me explain the connection and the differences:
Connection to Merge Sort
The optimization leverages a merge-like algorithm, which is similar to the merge step in merge sort. Here's how they're related:
Merge Sort:
Merge sort is a divide-and-conquer algorithm that sorts an array by:
Dividing the array into smaller subarrays.
Sorting each subarray.
Merging the sorted subarrays back together.
The merge step in merge sort combines two sorted arrays into a single sorted array in O(n) time.
Merge-like Algorithm in Index.join:
The optimization uses a similar merge-like algorithm to compute the join indexers for two sorted arrays (left and right keys).
Instead of creating a sorted output, it records the mappings (indexers) between the two arrays.
How the Merge-like Algorithm Works
The merge-like algorithm used in Index.join works as follows:
Initialize two pointers, one for each sorted array (left and right).
Compare the elements at the current positions of the pointers:
If they match, record the indices (indexers) and advance both pointers.
If the left element is smaller, advance the left pointer.
If the right element is smaller, advance the right pointer.
Repeat until all elements in both arrays are processed.
This is very similar to the merge step in merge sort, but instead of producing a sorted output, it produces indexers that map the left and right keys.
Why This is Efficient
The merge-like algorithm is efficient because:
It processes both arrays in a single pass (O(n) time).
It takes advantage of the sorted nature of the data to avoid unnecessary comparisons.
It doesn't require hashing or factorization, which are expensive operations.
Differences from Merge Sort
While the merge-like algorithm is inspired by merge sort, there are some key differences:
Purpose:
Merge sort: Sorts an array.
Merge-like algorithm in Index.join: Computes mappings (indexers) between two sorted arrays.
Output:
Merge sort: Produces a single sorted array.
Merge-like algorithm: Produces indexers (arrays of indices) that map the left and right keys.
Handling Duplicates:
Merge sort: Doesn't need to handle duplicates specially.
Merge-like algorithm: Needs to handle duplicates (e.g., for non-unique keys).
Example
Suppose we have two sorted arrays:
Left keys: [1, 3, 5, 7]
Right keys: [3, 5, 9]
The merge-like algorithm would:
Compare 1 (left) and 3 (right): 1 < 3, so advance the left pointer.
Compare 3 (left) and 3 (right): Match found! Record the indices and advance both pointers.
Compare 5 (left) and 5 (right): Match found! Record the indices and advance both pointers.
Compare 7 (left) and 9 (right): 7 < 9, so advance the left pointer.
End of left array.
The result would be:
Left indexer: [1, 2] (indices of 3 and 5 in the left array).
Right indexer: [0, 1] (indices of 3 and 5 in the right array).
Summary
The optimization is related to merge sort in that it uses a merge-like algorithm to process two sorted arrays.
However, it's not exactly the same as merge sort because:
It computes indexers (mappings) instead of producing a sorted output.
It handles duplicates and non-unique keys.
The merge-like algorithm is efficient because it processes the arrays in a single pass (O(n) time) and leverages the sorted nature of the data.
So, while the optimization isn't directly using merge sort, it's inspired by the same principles of efficiently merging sorted data.