I have an array a = [1, 2, 3, 4, 5, 6]
and b = [1, 3, 5]
and I'd like to map a
such that for every element in a
that's between an element in b
it will get mapped to the index of b
that is the upper range that a
is contained in. Not the best explanation in words but here's an example
a = 1 -> 0 because a <= first element of b
a = 2 -> 1 because b[0] < 2 <= b[1] and b[1] = 3
a = 3 -> 1
a = 4 -> 2 because b[1] < 4 <= b[2]
So the final product I want is f(a, b) = [0, 1, 1, 2, 2, 2]
I know I can just loop and solve for it but I was wondering if there is a clever, fast (vectorized) way to do this in pandas/numpy
Use python's bisect
module:
from bisect import bisect_left
a = [1, 2, 3, 4, 5, 6]
b = [1, 3, 5]
def f(_a, _b):
return [bisect_left(_b, i) for i in _a]
print(f(a, b))
bisect — Array bisection algorithm
This module provides support for maintaining a list in sorted order without having to sort the list after each insertion. For long lists of items with expensive comparison operations, this can be an improvement over the more common approach. The module is called bisect because it uses a basic bisection algorithm to do its work. The source code may be most useful as a working example of the algorithm (the boundary conditions are already right!).
The following functions are provided:
bisect.bisect_left(a, x, lo=0, hi=len(a))
Locate the insertion point for x in a to maintain sorted order. The parameters lo and hi may be used to specify a subset of the list which should be considered; by default the entire list is used. If x is already present in a, the insertion point will be before (to the left of) any existing entries. The return value is suitable for use as the first parameter to
list.insert()
assuming that a is already sorted.The returned insertion point i partitions the array a into two halves so that
all(val < x for val in a[lo:i])
for the left side andall(val >= x for val in a[i:hi])
for the right side.
Reference: https://docs.python.org/3/library/bisect.html
bisect is faster: the solution assumes lists are sorted
a = [1, 2, 3, 4, 5, 6]
b = [1, 3, 5]
inds=[min(bisect_left(b,x),len(b)-1) for x in a]
returns
[0, 1, 1, 2, 2, 2]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With