Search code examples
pythonpython-3.xpandasgeolocationgeo

How do you use pandas and python to assess within how many geographic boxes the user is located?


I am trying to figure out how apps such as Uber and UbersEats operate and manage the logistics. And I am wondering how can we build a function to calculate within how many boxes the user is located. This is the data for users:

user_id,loc_lat,loc_lon
1,55.737564,37.345186
2,56.234564,37.234590
3,55.234578,36.295745

And this is the coordinates of boxes (places):

place_id,loc_lat,loc_lon,point_number
1,55.747022,37.787073,0
1,55.751713,37.784328,1
1,55.753878,37.777638,2
1,55.751031,37.779351,3
2,55.803885,37.458311,0
2,55.808677,37.464054,1
2,55.809763,37.461314,2
2,55.810840,37.458654,3

So for a user 1 it would be 2 places available and 0 for user 3. If you could point me in the right direction, I would be extremely grateful.


Solution

  • From the test cases of users: none of them are within the bounds of the boxes. Following the logic from How can I determine whether a 2D Point is within a Polygon?

    // p is your point, p.x is the x coord, p.y is the y coord
    if (p.x < Xmin || p.x > Xmax || p.y < Ymin || p.y > Ymax) {
        // Definitely not within the polygon!
    }
    

    Loading the DataFrame in Python:

    import pandas as pd
    columns = ['user_id','loc_lat','loc_lon','point_number']
    df = pd.DataFrame([[1,55.747022,37.787073,0],[1,55.751713,37.784328,1],[1,55.753878,37.777638,2],[1,55.751031,37.779351,3]], columns = columns)