Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - easy way to "comparison" map one array to another

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

like image 679
Michael Avatar asked Jun 14 '17 12:06

Michael


2 Answers

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 and all(val >= x for val in a[i:hi]) for the right side.

Reference: https://docs.python.org/3/library/bisect.html

like image 188
Mahdi Perfect Avatar answered Oct 20 '22 01:10

Mahdi Perfect


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]
like image 32
suvy Avatar answered Oct 20 '22 00:10

suvy